是否有任何可能檢測到任何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);
}
});
}
}
任何幫助請:D –