【问题标题】:Angular 5 HttpInterceptor this.interceptor.intercept is not a functionAngular 5 HttpInterceptor this.interceptor.intercept 不是函数
【发布时间】:2018-05-16 11:39:47
【问题描述】:

我创建了一个 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);
    }
}

这就是 app.moudle.ts

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

请求示例

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;
                }
            });
    }

【问题讨论】:

    标签: angular angular5 angular-http-interceptors


    【解决方案1】:

    请试试这个:

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

    【讨论】:

    猜你喜欢
    • 2020-04-18
    • 2018-05-14
    • 2018-10-14
    • 2018-12-02
    • 2018-11-20
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多