2017-12-02 27 views
0

すべてのxhr要求に「withCredentials:true」を追加するためにHttpInterceptor(Angular5)を作成しました。しかし、私は任意のHTTP要求を呼び出すたびに、私は次のエラーを取得:角度5 HttpInterceptor this.interceptor.interceptは関数ではありません

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

です

Requesトン例

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

答えて

4

これを試してください:

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

ありがとう!これはうまくいった。 – GuyChabra