I have 2 tokens. token_a lasts a very long time and is used to generate token_b. token_b expires every 15 minutes.
A user can navigate to a module however before they can do this i have a guard which checks whether the token_b is expired or not.However, they could already be within the module and making api calls that do not require a page change. My understanding is that guards are mainly used to protect routes.
How do i solve this problem of checking if a token is expired before making a http request.
api.service.ts
import { Injectable } from '@angular/core';
import { environment } from './../../../../environments/environment';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class ApiService {
constructor(
private http: HttpClient,
) { }
private setHeaders(): HttpHeaders {
const headersConfig = {
'Content-Type': 'application/json',
// 'Accept': 'application/json plain/text'
};
const token = localStorage.getItem('profile_token');
if (token) {
headersConfig['Authorization'] = 'Bearer ' + token;
}
return new HttpHeaders(headersConfig);
}
private formatErrors(error: any) {
console.log(error);
return Observable.throw(error);
}
get(path: string, httpParams: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), params: httpParams })
.catch(this.formatErrors)
.map((res) => res);
}
put(path: string, body: Object = {}): Observable<any> {
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res) => res);
}
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(
`${environment.api_url}${path}`,
body,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res) => res);
}
delete(path): Observable<any> {
return this.http.delete(
`${environment.api_url}${path}`,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res) => res);
}
}