this.interceptor.intercept 不是函数 Angular 8

Lin*_*int 4 http xmlhttprequest angular

我正在尝试jsonwebtokens在我的 Angular 项目中实现,为此我使用了一个HttpInterceptors. 不幸的是,我面临以下错误:

this.interceptor.intercept 不是函数

我已经搜索了其他 Stackoverflow 线程以应用他们的解决方案,但到目前为止我无法使其工作。

这是我的 TokenInterceptorService

import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {

  constructor() { }
  intercept(req, next) {
    let tokenizedReq = req.clone({
      setHeaders: {
        Authorization: 'Bearer xx.yy.zz'
      }
    });
    return next.handle(tokenizedReq)
  }
}

Run Code Online (Sandbox Code Playgroud)

这是我的 app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule, Routes } from '@angular/router';
import { MatMomentDateModule } from '@angular/material-moment-adapter';
// import { MatButtonModule } from '@angular/material/button';
import { MatButtonModule, MatFormFieldModule, MatInputModule, MatRippleModule } from '@angular/material';
import { MatIconModule } from '@angular/material/icon';
import { MatDialogModule, MAT_DIALOG_DATA, MatDialogRef, MatDialog } from '@angular/material/dialog';
import { TranslateModule } from '@ngx-translate/core';
import { MatSelectModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { FlexLayoutModule } from '@angular/flex-layout';
import 'hammerjs';

import { FuseModule } from '@fuse/fuse.module';
import { FuseSharedModule } from '@fuse/shared.module';
import { FuseProgressBarModule, FuseSidebarModule, FuseThemeOptionsModule } from '@fuse/components';

import { fuseConfig } from 'app/fuse-config';

import { AppComponent } from 'app/app.component';
import { LayoutModule } from 'app/layout/layout.module';
import { SampleModule } from 'app/main/sample/sample.module';
import { AddSalesPersonComponent } from './layout/components/Sales/add-sales-person/add-sales-person.component';
import { LoginComponent } from './layout/components/login/login.component';
import { MasterLayoutComponent } from './master-layout/master-layout.component';
import { NewLoanComponent } from './layout/components/loan/new-loan/new-loan.component';
import { ListSalesComponent } from './layout/components/Sales/list-sales/list-sales.component';
import { NewCustomerComponent } from './layout/components/customer/new-customer/new-customer.component';
import { CustomerListComponent } from './layout/components/customer/customer-list/customer-list.component';
import { NewOrganizationComponent } from './layout/components/organization/new-organization/new-organization.component';
import { ListOrganizationComponent } from './layout/components/organization/list-organization/list-organization.component';
import { NewProductComponent } from './layout/components/products/new-product/new-product.component';
import { ProductListComponent } from './layout/components/products/product-list/product-list.component';
import { NewAdminComponent } from './layout/components/admin/new-admin/new-admin.component';
import { ListAdminComponent } from './layout/components/admin/list-admin/list-admin.component';
import { LoanListComponent } from './layout/components/loan/loan-list/loan-list.component';
import { ReceivePaymentComponent } from './layout/components/payments/receive-payment/receive-payment.component';
import { MakePaymentComponent } from './layout/components/payments/make-payment/make-payment.component';
import { AuthGuard } from './guards/auth.guard';
import { TokenInterceptorService } from './services/token/token-interceptor.service';

const appRoutes: Routes = [
    {
        path: '',
        component: MasterLayoutComponent,
        children: [
            {
                path: '',
                redirectTo: '/login',
                pathMatch: 'full'
            },
            {
                path: 'saveSalesPerson',
                component: AddSalesPersonComponent
            },
            {
                path: 'searchsalesperson',
                component: ListSalesComponent
            },
            {
                path: 'newcustomer',
                component: NewCustomerComponent
            },
            {
                path: 'searchcustomer',
                component: CustomerListComponent,
                canActivate: [AuthGuard]
            },
            {
                path: 'neworganization',
                component: NewOrganizationComponent
            },
            {
                path: 'searchorganization',
                component: ListOrganizationComponent
            },
            {
                path: 'newproduct',
                component: NewProductComponent
            },
            {
                path: 'searchpoduct',
                component: ProductListComponent
            },
            {
                path: 'newloan',
                component: NewLoanComponent
            },
            {
                path: 'searchLoan',
                component: LoanListComponent
            },
            {
                path: 'newadmin',
                component: NewAdminComponent
            },
            {
                path: 'searchadmin',
                component: ListAdminComponent
            },
            {
                path: 'receivePayments',
                component: ReceivePaymentComponent
            },
            {
                path: 'makePayments',
                component: MakePaymentComponent
            },
        ]
    },
    {
        path: 'login',
        component: LoginComponent,
    },

    {
        path: '**',
        redirectTo: 'salesperson'
    }
];

@NgModule({
    imports: [
        BrowserModule,
        FlexLayoutModule,
        MatButtonModule,
        MatFormFieldModule,
        FormsModule,
        MatInputModule,
        MatRippleModule,
        MatSelectModule,
        BrowserAnimationsModule,
        HttpClientModule,
        MatDialogModule,
        RouterModule.forRoot(appRoutes),

        TranslateModule.forRoot(),

        // Material moment date module
        MatMomentDateModule,

        // Material
        MatButtonModule,
        MatIconModule,

        // Fuse modules
        FuseModule.forRoot(fuseConfig),
        FuseProgressBarModule,
        FuseSharedModule,
        FuseSidebarModule,
        FuseThemeOptionsModule,

        // App modules
        LayoutModule,
        SampleModule
    ],
    declarations: [
        AppComponent,
        MasterLayoutComponent
    ],
    exports: [
        MatButtonModule,
        MatFormFieldModule,
        MatInputModule,
        MatRippleModule,

    ],
    bootstrap: [
        AppComponent
    ],
    providers: [AuthGuard, {
        provide: HTTP_INTERCEPTORS,
        useClass: TokenInterceptorService,
        multi: true
    }, { provide: MatDialogRef, useValue: {} },
    ]

})
export class AppModule {
}

Run Code Online (Sandbox Code Playgroud)

为了检查起见,我对临时令牌进行了硬编码,但是一旦我解决了这个问题,我就会实现真正的令牌。

Jos*_*man 7

由于您是在 app.module.ts中手动提供拦截器,因此请尝试以下操作:

@Injectable()
Run Code Online (Sandbox Code Playgroud)

代替

@Injectable({
  providedIn: 'root'
})
Run Code Online (Sandbox Code Playgroud)

同样在拦截器中检查所有依赖项是否已正确导入,最后但并非最不重要的是请不要忘记使用类型(这个与您的问题无关,只是一个友好的建议)

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class TokenInterceptorService implements HttpInterceptor {
  constructor() {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}
Run Code Online (Sandbox Code Playgroud)