My app uses firebase to authenticate users. I use the token provided in header for making request to the backend server. Initially, i stored the token in a variable and all my service files access this variable for the token to add it to header before making request.
This was not of much use as expiry of the token cannot be checked this way and eventually server returned error for the requests. Now, Iam trying to get token from firebase provided method but since this is a 'promise', the control flow doesn't wait for the response and as a result blank token is sent in the request.
//in a general service file
getData(): Observable<any> {
let tokenOptions = this.authService.getTokenHeader();
return this.http.get(this.endPoints.dataUrl, tokenOptions)
.map(res => {
this.data = res.json().data;
return this.data;
})
.catch(( error: any ) => Observable.throw( error.json().error || 'Server error' ))
}
//in authService file
getTokenHeader() {
const token = this.getToken();
console.log(token);
let tokenHeader = new Headers({ 'Authorization': token });
tokenHeader.append('Content-Type', 'application/json');
let tokenOptions = new RequestOptions({ headers: tokenHeader });
return tokenOptions;
}
getToken() {
firebase.auth().currentUser.getIdToken(true)
.then(token => return token);
}
I have tried various methods like trying to returning tokenheader within then response of firebase method but all show type errors. I have been trying to get this solved from past two days. Since, this is a general workflow i think somebody can help me with a standard solution.