I am new to angular, so I though of using firebase for storing user tokens which will be accessed on calling an interceptor for modifying requests headers.
I have added firebase function in the constructor and HttpHandler
function separately,
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private token: any = null;
constructor() {
firebase.database().ref(`currentUserDetails/${localStorage.getItem('sn')}`).once('value', (snap) => {
if(snap.exists()){
this.token = snap.val().token;
}
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(this.token) {
request = request.clone({
setHeaders: {
Authorization: this.token
}
});
}
console.log(this.token) // this is null
return next.handle(request)
}
}
The problem is that the intercept
function executes before complete execution of constructor
function. So, this.token
is null.
I have tried using callback function, have tried async await
function and also, I have tried the solution given in stack overflow which is not succeeding.
Is there any solution to solve this issue?