I have a web application that need to use sometimes a Token to access my third partner endpoints.
This Token is located on my database, and is obtained in an endpoint at my own server.
I'm trying to build a structure that only request the token on my backend, the first time that some function that needs it is called. And when i already had the token, i'm gonna used it on my local variable.
export class Service {
private readonly api_url: string = environment.API_URL;
private token: string;
getToken(): Observable<any> {
// HTTP call to get the token on my own backend and return the token
}
partnerFirstFunction(): Observable<any> {
if (!this.token)
this.getToken().subscribe((response) => {
this.token = response;
var headers = new HttpHeaders({ 'Authorization': 'bearer ' + this.token });
return this.http.request<any>('POST', 'partnerUrl', { headers: headers }).pipe(map(response => {
return response;
}));
});
// I WANT TO PREVENT THE ABOVE CODE FROM REPEATING
else {
var headers = new HttpHeaders({ 'Authorization': 'bearer ' + this.token });
return this.http.request<any>('POST', 'partnerUrl', { headers: headers }).pipe(map(response => {
return response;
}));
}
}
partnerSecFunction(): Observable<any> {
if (!this.token)
this.getToken().subscribe((response) => {
this.token = response;
var headers = new HttpHeaders({ 'Authorization': 'bearer ' + this.token });
return this.http.request<any>('POST', 'partnerUrl', { headers: headers }).pipe(map(response => {
return response;
}));
});
// I WANT TO PREVENT THE ABOVE CODE FROM REPEATING
else {
var headers = new HttpHeaders({ 'Authorization': 'bearer ' + this.token });
return this.http.request<any>('PATCH', 'partnerUrl', { headers: headers }).pipe(map(response => {
return response;
}));
}
}
}
I tried to build a get/set to my token variable, making the "already existing" validation inside the get method, but when needed to request the token, the code continues without waiting the request.
private _token: string;
get token(): string {
if (this._token == null)
this.getToken().subscribe((response) => {
return this._token;
});
else
return this._token;
}