Created
March 24, 2018 02:59
-
-
Save prosoftwaredev/6c98c6905bdb48679ed8a1ea686f01a6 to your computer and use it in GitHub Desktop.
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 "@angular/core"; | |
import { Observable } from "rxjs/Observable"; | |
import { environment } from "../../environments/environment"; | |
import { Router } from "@angular/router"; | |
import { HttpClient } from "@angular/common/http"; | |
import { catchError } from "rxjs/operators"; | |
import "rxjs/add/observable/throw"; | |
import { AuthDataStorage } from "../../common/auth-data.storage"; | |
export const TOKEN_STORAGE_KEY = "token"; | |
@Injectable() | |
export class ApiService { | |
private apiUrl = environment.apiEndpoint; | |
constructor(private http: HttpClient, private router: Router, private authDataStorage: AuthDataStorage) { | |
} | |
get<T>(url: string, options?: any): Observable<T | any> { | |
const opts = options || {}; | |
return this.http | |
.get(`${this.apiUrl}/${url}`, opts) | |
.pipe( | |
catchError(this.processError.bind(this)) | |
); | |
} | |
post<T>(url: string, body: any, options?: any): Observable<T | any> { | |
const opts = options || {}; | |
return this.http | |
.post(`${this.apiUrl}/${url}`, body, opts) | |
.pipe( | |
catchError(this.processError.bind(this)) | |
); | |
} | |
put<T>(url: string, body: any, options?: any): Observable<T | any> { | |
const opts = options || {}; | |
return this.http | |
.put(`${this.apiUrl}/${url}`, body, opts) | |
.pipe( | |
catchError(this.processError.bind(this)) | |
); | |
} | |
private processError(err: Response, caught?) { | |
console.log(err); | |
if (err.status === 401) { | |
this.authDataStorage.unsetToken(); | |
return this.router.navigate(["/login"], { queryParams: { returnUrl: this.router.routerState.snapshot.url } }); | |
} | |
return Observable.throw(new Error(`${err.status} ${err.statusText}`)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment