Last active
August 3, 2021 16:13
-
-
Save otonielguajardo/38942a2f8172c85501a305110c42cae9 to your computer and use it in GitHub Desktop.
Directus Angular service layer
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 { HttpClient, HttpHeaders } from '@angular/common/http'; | |
import { Observable } from 'rxjs'; | |
import { environment } from '@env/environment'; | |
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class ApiService { | |
constructor(private http: HttpClient) {} | |
get access_token() { | |
return localStorage.getItem(environment.ACCESS_TOKEN_ALIAS); | |
} | |
set access_token(access_token) { | |
if (access_token) localStorage.setItem(environment.ACCESS_TOKEN_ALIAS, access_token); | |
} | |
get refresh_token() { | |
return localStorage.getItem(environment.REFRESH_TOKEN_ALIAS); | |
} | |
set refresh_token(refresh_token) { | |
if (refresh_token) localStorage.setItem(environment.REFRESH_TOKEN_ALIAS, refresh_token); | |
} | |
public request(method: string, endpoint: string, body?: any): Observable<any> { | |
let headers: HttpHeaders; | |
if (this.access_token !== null) { | |
headers = new HttpHeaders({ | |
Authorization: `Bearer ${this.access_token}`, | |
'Content-Type': 'application/json', | |
}); | |
} | |
return this.http.request(method, `${environment.API_URL}/${endpoint}`, { | |
body, | |
headers, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment