代码之家  ›  专栏  ›  技术社区  ›  GuyChabra

角度5 HttpInterceptor this。拦截器。拦截不是一个函数

  •  3
  • GuyChabra  · 技术社区  · 8 年前

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

    @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;
                    }
                });
        }
    1 回复  |  直到 8 年前
        1
  •  15
  •   Developer Thing    8 年前

    请尝试以下操作:

    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: GeneralInterceptor,
            multi: true
        },
    
    推荐文章