Skip to content

Instantly share code, notes, and snippets.

@otonielguajardo
Last active August 3, 2021 16:13
Show Gist options
  • Save otonielguajardo/38942a2f8172c85501a305110c42cae9 to your computer and use it in GitHub Desktop.
Save otonielguajardo/38942a2f8172c85501a305110c42cae9 to your computer and use it in GitHub Desktop.
Directus Angular service layer
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