I previously wrote a code in Angular 4 that was functioning flawlessly, however, after migrating to Angular 6, a part of it seems to be broken. I would greatly appreciate any assistance with this issue.
One problematic area is within the AuthService
class:
export class AuthService {
private loggedIn = new BehaviorSubject<boolean>(false);
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);
}
}
The code snippet above showcases how I subscribe to the subject in my AppComponent
's 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 main problem arises when logging out - the AppComponent appropriately reacts to the observable. However, upon logging back in, there seems to be an issue where the component fails to acknowledge the change. Despite maintaining the code as it was during the Angular 4 implementation, I am unable to discern why the login event is not being triggered.