Interceptors in Angular2

后端 未结 3 773
说谎
说谎 2020-12-15 07:32

I am trying to build a demo app on Angular2.beta.0 which would have login mechanism and then all the other API calls would have the acquired session token s

3条回答
  •  独厮守ぢ
    2020-12-15 08:09

    first in app.module.ts add following line at providers array:

        {provide : Http, useFactory: (xhrBackend: XHRBackend, requestOptions:  RequestOptions) => new HttpInterceptor(xhrBackend, requestOptions),deps:  [XHRBackend, RequestOptions]}
    

    Create HttpIntreceptor file with

        import {Http, RequestOptionsArgs, RequestOptions, Response, Request, ConnectionBackend} from "@angular/http";
        import {Observable} from "rxjs/Observable";
        import "rxjs/add/operator/catch"; 
        import "rxjs/add/observable/throw";
        import "rxjs/add/observable/empty";
        import {Router} from "@angular/router";
    
        export class HttpInterceptor extends Http {
            constructor(backend: ConnectionBackend, defaultOptions: RequestOptions,    private _router: Router) {
                super(backend, defaultOptions);
            }
    
            request(url: string | Request, options?: RequestOptionsArgs):      Observable {
                return this.intercept(super.request(url, options));
            }
    
            get(url: string, options?: RequestOptionsArgs): Observable {
                return this.intercept(super.get(url,options));
            }
    
            post(url: string, body: string, options?: RequestOptionsArgs): Observable {
                return this.intercept(super.post(url, body, options));
            }
    
            put(url: string, body: string, options?: RequestOptionsArgs): Observable {
                return this.intercept(super.put(url, body, options));
            }
    
            delete(url: string, options?: RequestOptionsArgs): Observable {
                return this.intercept(super.delete(url, options));
            }
    
            intercept(observable: Observable): Observable {
                return observable.catch((err, source) => {
                });
            }
        }
    

提交回复
热议问题