Angular 4.2.5中的HTTP拦截器

时间:2017-09-15 15:40:00

标签: javascript angular

拦截

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

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req);
  }
}

错误

ERROR in C:/Users/mypc/workspace/angularapp/src/app/app.module.ts (5,9): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HTTP_INTERCEPTORS'.

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (2,9): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HttpEvent'.

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (2,20): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HttpInterceptor'.

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (2,37): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HttpHandler'.

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (2,50): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HttpRequest'.

ERROR in C:/Users/mypc/workspace/angularapp/src/app/interceptors/401.interceptor.ts (6,56): Cannot find name 'Observable'.

ERROR in C:/Users/mypc/workspace/angularapp/src/app/app.module.ts (5,9): Module '"C:/Users/mypc/workspace/angularapp/node_modules/@angular/http/http"' has no exported member 'HTTP_INTERCEPTORS'.

2 个答案:

答案 0 :(得分:0)

正确的包裹是@angular/common/http。而且,顺便说一下,我认为它仅适用于4.3.x版本。 @angular/http将来会被弃用。

答案 1 :(得分:-1)

import { Injectable } from "@angular/core";
import { ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, Headers } from "@angular/http";
import { Observable } from "rxjs/Rx";
import { Router } from '@angular/router';
import { environment } from "../../../environments/environment";
import {LoaderService} from '../loader/loader.service';
import {LocalStorageService} from '../_services/localstorage.service';

@Injectable()
export class InterceptedHttp extends Http {
    router: Router;
    loaderService:LoaderService;
    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions,private _router: Router,
        private _loaderService:LoaderService,private _localStorageService:LocalStorageService) {
        super(backend, defaultOptions);
        this.router = _router;
        this.loaderService=_loaderService;
    }    
    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        url = this.updateUrl(url);
        return this.intercept(super.get(url, this.getRequestOptionArgs(options)));
    }

    post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        url = this.updateUrl(url);
        let data=body;//url.endsWith('token')?body:JSON.stringify(body);//fr token url only
        return this.intercept(super.post(url, data, this.getRequestOptionArgs(options)));
    }

    put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        url = this.updateUrl(url);
        return this.intercept(super.put(url, body, this.getRequestOptionArgs(options)));
    }

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
        url = this.updateUrl(url);
        return this.intercept(super.delete(url, this.getRequestOptionArgs(options)));
    }

    private updateUrl(req: string) {
        this.showLoader();
        return environment.origin +'/'+ req;
    }

    private getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
        if (options == null) {
            options = new RequestOptions();
        }
        if (options.headers == null) {
            options.headers = new Headers();
        }
        options.withCredentials=true;
        options.headers.append('Content-Type', 'application/json');
        options.headers.append('Authorization', 'Bearer ' + this._localStorageService.getAuthToken());
        //options.headers.append('Content-Type', 'application/x-www-form-urlencoded');
        return options;
    }


    private onEnd(): void {
        this.hideLoader();
    }
    private showLoader(): void {
        this.loaderService.show();
    }
    private hideLoader(): void {
        this.loaderService.hide();
    }

    intercept(observable: Observable<Response>): Observable<Response> {
        //return observable.map(response => response.json())
        return observable.catch((err, source) => {
            if (err.status === 401) {
                alert('You are not authorized to access the resource');
                //setTimeout(() => this.router.navigate(['/login']), 3000);
                setTimeout(() => document.location.href='/login', 3000);                
                return Observable.empty();
            }
            else if (err.status === 404) {
                console.log(['http service',err]);
                 document.location.href='/not-found';                
                return Observable.empty();
            }
             else {
                console.log(['htto errir',err]);
                err.errors=this.parseErrors(err);
                return Observable.throw(err);
            }
        }).finally(() => {
            this.onEnd();
        });
    }

    parseErrors(response): Array<string>
    {
        let errors:Array<string>=new Array<string>();

        if (response) {
            response=JSON.parse(response._body);
            if (response.error_description) {
                errors.push(response.error_description);
            }
            if (response.message) {
                errors.push(response.message);
            }
            for (var key in response.modelState) {
                for (var i = 0; i < response.modelState[key].length; i++) {
                    errors.push(response.modelState[key][i]);
                }
            }
        } else {
            errors.push('Server response null');
        }
        return errors;
    }
}

你可以在Angular4中创建像这样的HttpInterceptor和HttpFactory,如下所示:

import {XHRBackend, Http, RequestOptions} from "@angular/http";
import {Router} from "@angular/router";
import {InterceptedHttp} from "./http.interceptor";
import {LoaderService} from '../loader/loader.service';
import {LocalStorageService} from '../_services/localstorage.service';

export function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions,router:Router,
    loaderService:LoaderService,localStorageService:LocalStorageService): Http {
    return new InterceptedHttp(xhrBackend, requestOptions,router,loaderService,localStorageService);
}

如果您不需要相应删除,我正在使用本地存储

{
    provide: Http,
    useFactory: httpFactory,
    deps: [XHRBackend, RequestOptions,Router,LoaderService,LocalStorageService ]
},

在提供商内的app.module.ts中进行如下调用。