2016-10-10 96 views
1

是否有任何可能檢測到任何http請求的開始,以及何時在angular2中完成調用? 這是我的自定義HTTP服務:檢測任何http請求的開始,並在angular2中完成所有請求

import {Injectable, Inject} from "@angular/core"; 
import { Http, Response, Headers, RequestOptions } from "@angular/http"; 
import { StorageServiceClass } from "../storage.service"; 
import "rxjs/add/operator/map"; 
import * as Cookies from "js-cookie"; 

import { Observable } from "rxjs/Rx"; 
import { Router } from "@angular/router"; 


@Injectable() 
export class HttpClient { 

    public storage: StorageServiceClass; 

    private http: Http; 
    private router: Router; 

    constructor(private _http: Http, _router: Router, private _storage: StorageServiceClass) { 
     this.http = _http; 
     this.router = _router; 
     this.storage = _storage; 
    } 

    public setToken() { 
     let token = Cookies.get("authToken"); 
     if (token !== "undefined" && token !== undefined) { 
      this.storage.setAuthToken(token); 
     } 
    } 

    public removeStorageAndCookies() { 
     Cookies.remove("authToken"); 
     this.storage.removeAuthToken(); 
    } 

    public createAuthorizationHeader(headers: Headers) { 
     let token = this.storage.getAuthToken(); 
     headers.append("Accept", "application/json"); 
     headers.append("Content-Type", "application/json"); 

     if (token !== null && token !== undefined) { 
      headers.append("Authorization", "JWT " + token); 
     } 
    } 

    public post(url: string, data: any, options?: RequestOptions) { 
     let headers = new Headers(); 
     if (options !== undefined) { 
      headers = options.headers; 
     } 
     this.createAuthorizationHeader(headers); 
     let dataResp = this.intercept(this.http.post(url, data, { headers: headers, withCredentials: true })); 
     this.setToken(); 
     return dataResp; 
    } 


    public put(url: string, data: any, options?: RequestOptions) { 
     let headers = new Headers(); 
     if (options !== undefined) { 
      headers = options.headers; 
     } 
     this.createAuthorizationHeader(headers); 
     let dataResp = this.intercept(this.http.put(url, data, { headers: headers, withCredentials: true })); 
     this.setToken(); 
     return dataResp; 
    } 

    public delete(url: string, options?: RequestOptions) { 
     let headers = new Headers(); 
     if (options !== undefined) { 
      headers = options.headers; 
     } 
     this.createAuthorizationHeader(headers); 
     let dataResp = this.intercept(this.http.delete(url, { headers: headers, withCredentials: true })); 
     this.setToken(); 
     return dataResp; 
    } 


    public get(url: string, data?: any, options?: RequestOptions) { 
     let headers = new Headers(); 
     if (options !== undefined) { 
      headers = options.headers; 
     } 
     this.createAuthorizationHeader(headers); 

     let urlParams = ""; 
     if (data) { 
      urlParams = jQuery.param(data); 
     } 

     let dataResp = this.intercept(this.http.get(url, { 
      headers: headers, search: urlParams, withCredentials: true 
     })); 
     this.setToken(); 
     return dataResp; 
    } 

    public intercept(observable: Observable<Response>): Observable<Response> { 
     return observable.catch((err, source) => { 
      if (err.status === 401) { 
       this.removeStorageAndCookies(); 
       this.router.navigate(["login"]); 
       return Observable.empty(); 
      } else { 
       return Observable.throw(err); 
      } 
     }); 
    } 

} 
+0

任何幫助請:D –

回答

2

在角2這種操作提供httpwrapper服務的推薦方式。這看起來像這樣:

@Injectable() 
export class CustomHttp extends Http { 
    private activeCalls: number; 
    private store: Store<ApplicationState>; 

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, store: Store<ApplicationState>) { 
     super(backend, defaultOptions); 
     this.store = store; 
     this.activeCalls = 0; 
    } 

    get(url: string, options?: RequestOptionsArgs): Observable<Response> { 
     this.httpCallRequested(); 

     return super.get(url, options).finally(
      () => { 
       this.httpCallReady(); 
      } 
     ); 
    } 
} 

這是一個不完整的例子。在這裏找到完整的一個:https://github.com/brechtbilliet/winecellar/blob/master/src/app/customHttp.ts

該類包裝所有http調用,並允許您在執行前後執行某些操作。 要使用這個包裝到處,而不是普通的HTTP服務,你應該在你的應用程序模塊中提供這個類。這可以這樣完成:

@NgModule({ 
    imports: [BrowserModule, AboutModule, AuthenticationModule, CommonLogicModule, StockModule, routing], 
    declarations: [ApplicationContainer], 
    exports: [ApplicationContainer], 
    providers: [ 
     AppSandbox, 
     { 
      provide: Http, 
      useFactory: customHttpFactory, 
      deps: [XHRBackend, RequestOptions, Store] 
     } 
    ] 
}) 

注意提供者部分。這個模塊下面的每個模塊都會得到一個httpWrapper的實例,如果他們通過角度2 DI機制注入'Http'的話。

+0

嗯......謝謝...我對你的解決方案感興趣(y) –