Last active
October 23, 2020 02:30
-
-
Save lucassus/d42069763c81a6e6bc68046793893c2c to your computer and use it in GitHub Desktop.
Angular 2 http retry logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from "angular2/core"; | |
import { Headers, Http, Response, RequestOptionsArgs, URLSearchParams, RequestMethod } from "angular2/http"; | |
import { Observable } from "rxjs/Observable"; | |
import { SessionStorage } from "./session_storage.service"; | |
import { Router } from "angular2/router"; | |
@Injectable() | |
export class HttpClient { | |
constructor( | |
private http: Http, | |
private router: Router, | |
private sessionStorage: SessionStorage) {} | |
public get(url: string, search?: URLSearchParams): Observable<Object> { | |
return this.request(url, { method: RequestMethod.Get, search }) | |
.map((response: Response) => response.json()); | |
} | |
public post(url: string, data?: Object): Observable<Object> { | |
return this.request(url, { method: RequestMethod.Post }, data) | |
.map((response: Response) => response.json()); | |
} | |
public put(url: string, data?: Object): Observable<Object> { | |
return this.request(url, { method: RequestMethod.Put }, data) | |
.map((response: Response) => response.json()); | |
} | |
public delete(url: string): Observable<Object> { | |
return this.request(url, { method: RequestMethod.Delete }); | |
} | |
private request(url: string, options: RequestOptionsArgs, data?: Object): Observable<Response> { | |
options.headers = new Headers(); | |
if (this.sessionStorage.accessToken) { | |
options.headers.append("Authorization", `Bearer ${this.sessionStorage.accessToken}`); | |
} | |
if (options.method === RequestMethod.Post || options.method === RequestMethod.Put) { | |
options.headers.append("Content-Type", "application/json"); | |
} | |
if (data) { | |
options.body = JSON.stringify(data); | |
} | |
// TODO write specs for the refresh logic | |
// TODO refactor | |
return this.http.request(url, options).catch((error) => { | |
if (error.status === 403) { | |
const params = { refreshToken: this.sessionStorage.refreshToken, admin: true }; | |
return this.post("/api/auth/refresh", params) | |
.flatMap((data: any) => { | |
this.sessionStorage.accessToken = data.accessToken; | |
return this.request(url, options, data); | |
}) | |
.catch(() => { | |
this.sessionStorage.destroy(); | |
return Observable.fromPromise(this.router.navigate(["/Login"])); | |
}); | |
} | |
return Observable.throw(error); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, from that I know we need
flatMap
. It's the key.