Angular 5 HttpInterceptor this.interceptor.intercept不是函数

时间:2017-12-02 14:48:12

标签: angular angular5 angular-http-interceptors

我创建了一个HttpInterceptor(Angular5),以便为每个xhr请求添加" withCredentials:true"。但每次我调用任何http请求时,都会收到以下错误:

ERROR TypeError: this.interceptor.intercept is not a function
at HttpInterceptorHandler.handle (http.js:1777)
at HttpXsrfInterceptor.intercept (http.js:2470)
at HttpInterceptorHandler.handle (http.js:1777)
at MergeMapSubscriber.eval [as project] (http.js:1447)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:91)
at ScalarObservable._subscribe (ScalarObservable.js:51)
at ScalarObservable.Observable._trySubscribe (Observable.js:172)
at ScalarObservable.Observable.subscribe (Observable.js:160)



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

@Injectable()
export class GeneralInterceptor implements HttpInterceptor{
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const cRequest = req.clone({
            withCredentials: true
        });
        return next.handle(cRequest);
    }
}
&#13;
&#13;
&#13;

这是app.moudle.ts

&#13;
&#13;
@NgModule({
    declarations: [...],
    imports: [
        ...
        HttpClientModule,
        ...
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useValue: GeneralInterceptor,
            multi: true
        },
        UsersService
      ],
    bootstrap: [AppComponent]
})
&#13;
&#13;
&#13;

请求示例

&#13;
&#13;
login(username: string, password: string, remember: boolean){
        return this.http.post('http://localhost:8000/login', {username: username, password: password, remember:remember})
            .map((data: any) => {
                if('error' in data){
                    this.user = null;
                    return false;
                }else{
                    this.user = data.user;
                    return true;
                }
            });
    }
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:10)

请试试这个:

providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: GeneralInterceptor,
        multi: true
    },