Whenever I attempt to log in, the interceptors fail to set the header of the request because it runs before the .pipe() block of service. As a result, currentUser in interceptors is always null. ///////////////////////////////////////////////////////////////
http-interceptor.service.ts
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let currentUser = this.logInService.currentUserVal;
if (currentUser) {
req = this.addToken(req, currentUser);
}
return next.handle(req).pipe(catchError(this.handleError));
}
login.service.ts
public _currentUserSubject: BehaviorSubject<AuthRequest>;
public currentUser: Observable<AuthRequest>;
public get currentUserVal(): AuthRequest {
return this._currentUserSubject.value;
}
get currentUserToken() {
return this.currentUserVal;
}
constructor(private httpClient: HttpClient) {
this._currentUserSubject = new BehaviorSubject<AuthRequest>(this.getUserFromLocalStorage());
this.currentUser = this._currentUserSubject.asObservable();
}
generateToken(authRequest: AuthRequest) {
return this.httpClient.post<any>(`${this.glolabUrl}${this.authetnticationUrl}`, authRequest, { responseType: 'text' as 'json' })
.pipe( map(user => {
localStorage.setItem(this.JWT_TOKEN, JSON.stringify(user));
this._currentUserSubject.next(user);
return user;
})
);
}
login.component.ts
toAuthenticate() {
this.submitted = true;
if (this.loginForm.invalid) {
return;
}
this.spinner.show();
this.authSubscription = this.logInService.generateToken(this.authRequest)
// .pipe(first())
.subscribe(
data => {
this.logInService.autoritySubject.next(true);
this.router.navigate(['home']);
setTimeout(() => {
this.spinner.hide();
}, 500);
},
err => {
console.log(err);
this.spinner.show();
this.failedMessage = err;
this.failed = true;
this.onReset();
setTimeout(() => {
this.spinner.hide();
}, 500);
}
);
}