angular:HttpInterceptor没有捕获每个请求

时间:2017-09-26 06:31:33

标签: angular angular-http-interceptors

我编写了一个HttpInterceptor(Angular 4.3.6)来捕获所有请求并操纵一些头字段。我的问题是它没有抓住每个请求。可能是什么问题?

这是我的拦截器:

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

@Injectable()
export class AuthInterceptor implements HttpInterceptor {


    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        console.log('AuthInterceptor at work: ', req.url );

        const contentTypeReq = req.clone({
            headers: req.headers.set('Content-Type', 'application/json')
        });

        const token  = localStorage.getItem('token');
        if (token) {
            const authReq = contentTypeReq.clone({
                headers: req.headers.set('Authorization', 'Bearer ' + token)
            });
            return next.handle(authReq);
        }

        //debug - lazy loading
        //contentTypeReq.headers.keys()

        return next.handle(contentTypeReq);
    }
}


export const AuthInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true,
};

这里有一个未被捕获的请求:

...
login(username: string, password: string): Observable<boolean> {

        return this.http.post(environment.baseUrl + '/api/authenticate', JSON.stringify({ username: username, password: password }))
            .map((response: Response) => {
...

也许我对我应该重定向401错误的第二个拦截器有一些干扰:

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/empty';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/finally';
import {
    HTTP_INTERCEPTORS, HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor,
HttpRequest
} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

    constructor(private router: Router) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('Error interceptor at work: ', req.url);

        return next.handle(req)
            .do(event => {
                console.log('error interceptor in success', event);
            })
            .catch(err => {
                console.log('error interceptor in error', err);
                if (err instanceof HttpErrorResponse && err.status === 401) {

                    if (err.url !== '/login') {
                        console.log('redirecting to login...');
                        this.router.navigate(['/login']);
                    }
                }
                return Observable.throw(err);
                // or return Observable.empty();
            })
            .finally(() => {
                console.log('error finally');
            });
    }
}


export const ErrorInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true,
};

以下是我将它们集成到app.module中的方法:

  providers: [
    AuthGuard,
    AuthenticationService,
    UserService,
    MockBackend,
    BaseRequestOptions,
    GoogleAnalyticsEventsService,
    ErrorInterceptorProvider,
    AuthInterceptorProvider
  ]

2 个答案:

答案 0 :(得分:0)

我发现我的问题是,必须在Angular应用程序的每个模块中都提供拦截器,在这里您要拦截请求,而不仅仅是容器模块。

答案 1 :(得分:0)

我认为问题实际上出在您导入node_modules/node-jq/bin/jq上。

在这里查看我的完整答案:HTTP_INTERCEPTORS only in AppModule