I'm new to Angular 2. In the past I was able to solve all occuring problems with the docs. But at the moment I've a lot of problems with the observable pattern used by Angular 2, which comes with rxjs.
I have the following workflow. I implemented a user service, which takes care of basic steps like register, login, logout etc. In addition I have a header component, which will display the user menu. Based on the login of the user I want to update the menu (e.g. show logout or show login entries).
To accomplish this I make use of the BehaviorSubject from the rxjs-lib. Basically I just need a simple boolean value, called is loggedIn which will be updated everytime the user logs in or out. Here is a snippet from the service, component and the template.
export class UsersService {
private _loggedIn: BehaviorSubject<boolean> = new BehaviorSubject(false);
public loggedIn: Observable<boolean> = this._loggedIn.asObservable();
constructor(private _router: Router, public http: Http, @Inject('ApiUrl') private apiUrl: string) {
let token = localStorage.getItem('token');
if (token) {
this._loggedIn.next(!this.jwtHelper.isTokenExpired(token));
}
}
public login(body): void {
this.http.post(this.apiUrl + '/login', body, { headers: contentHeaders })
.subscribe(
response => {
localStorage.setItem('token', response.json().token);
this._loggedIn.next(!this.jwtHelper.isTokenExpired(response.json().token));
this._router.navigateByUrl('');
},
error => {}
);
}
public logout(): void {
localStorage.removeItem('token');
this._loggedIn.next(false);
this._router.navigateByUrl('/login');
}
}
export class HeaderComponent {
loggedIn: boolean = false;
private _subscription: any;
constructor(private _users: UsersService) {
this._subscription = this._users.loggedIn.subscribe((value) => {
this.loggedIn = value;
});
}
The value within the header component is updated, when the app is bootstrapped and also when the user logs out. The problem is the POST call within the login method. It seems that next() is never called. But other stuff within the callback like this._router.navigateByUrl(''); is called although.
I'm not sure what I'm doing wrong here? Do I have to create a new observable within the callback or should login itself return a observable?
Any hint is appreciated! thx!
edit
stackoverflow is funny. after I published the question I immediatley got proposals from other questions. But before I was searching and I cannot find an answer. The problem was that I injected the service multiple times, instead of just injecting the service during the bootstrap.
Found the solution here: Issue with RxJs BehaviorSubject's subscriber not being notified of value change
Nonetheless is this a reasonable pattern to notify components of updates at all?