How do I subscribe a global variable to a BehaviorSubject?
How do I subscribe a global variable to a BehaviorSubject?
I'm building a login function and I want certain buttons in the app.component template to appear the moment the user has logged in. I am trying to use BehaviorSubject for this. I'm using an *ngIf for the buttons in the template and the condition is a variable called loggedIn. However when I try to initialize the loggedIn variable with the result of the SubjectBehavior subscription i get the error:
*ngIf
loggedIn
ERROR in app.component.ts(10,3): error TS2322: Type 'Observable<boolean>' is not assignable to type 'boolean'.
I don't know whats causing this because I am returning a boolean, not an observable. Here is the code of app.component:
export class AppComponent {
private loggedIn: boolean = this.loginService.isLoggedIn().pipe(
map((isLoggedIn: boolean) => { // {3}
if (!isLoggedIn){
return false;
}
return true;
}));
constructor(private loginService: LoginService){}
logout():void{
this.loginService.logout();
}
}
and heres the relevant code of the loginService:
isLoggedIn():BehaviorSubject<boolean>{
return this.loggedIn;
}
login(username: string, password: string): Observable<boolean> {
return this.http.post(this.authUrl, JSON.stringify({username: username, password: password}), {headers: this.headers}).map((response: Response) => {
// login successful if there's a jwt token in the response
let token: any = response.json().token;
if (token) {
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));
this.loggedIn.next(true);
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
}).catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
2 Answers
2
Since you are using a Behavior Subject, you don't have to call the function agian, you can directly use the Subject as follows,
login() {
this.loginService.login(this.user.name,this.user.password).subscribe(
(response) => {
this.loginService.loggedIn.next(true);
this.router.navigate(['/home']);
}, (error) => {
this.loginService.loggedIn.next(false);
if (error.status == 400) {
this.showErrorAlert();
} else {
console.log(error);
}
});
}
The correct answer is that i should use the subscribe method instead of pipe like so:
constructor(private loginService: LoginService){
this.loginService.isLoggedIn().subscribe((isLoggedIn: boolean) =>
{
if (!isLoggedIn){
this.loggedIn = false;
}
this.loggedIn = true;
})
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.