I have a code that I wrote back in Angular 4 and it worked perfectly, now part of it is broken in Angular 6 and I appreciate some help.
I have an AuthService
class:
export class AuthService {
private loggedIn = new BehaviorSubject<boolean>(false);
isUserLoggedIn(): Observable<boolean> {
return this.loggedIn.asObservable();
}
isUserLoggedIn(): Observable<boolean> {
return this.loggedIn.asObservable();
}
login(username: string, password: string) {
let body =
{
username: username,
password: password
};
return this._http.post(Settings.apiEndpoint + "users/authenticate", body)
.map(res => {
localStorage.setItem('token', res["token"]);
localStorage.setItem('username', res["username"]);
this.isLoggedIn = true;
this.loggedIn.next(true);
return res;
})
.catch(error => {
this.clearAuthData();
return Observable.throw(error)
});
}
logout() {
localStorage.clear();
this.isLoggedIn = false;
this.loggedIn.next(this.isLoggedIn);
}
}
and in my AppComponent
, I subscribe to this subject like this in the ngOnInit:
this._auth.isUserLoggedIn()
.subscribe(
d => {
console.log("d here", d);
if (d)
{
this.isLoggedIn = true;
this.username = this._auth.getUsername();
}
else {
this.isLoggedIn = false;
}
},
d => {
console.log("error.");
},
() => {
console.log("bull.");
}
);
The issue is when I logout, the AppComponent does react to the observable, but when I login it doesn't. The code is untouched as far as I can tell from what it was in Angular 4, so I cannot figure out why it is not firing.