I configure service to track registered users. This service returns the Observable and all components that subscribe to it are notified (so far only one component subscribes to it).
Services:
private subject = new Subject<any>(); sendMessage(message: boolean) { this.subject.next( message ); } getMessage(): Observable<any> { return this.subject.asObservable(); }
Root application component: (this component subscribes to observable)
ngAfterViewInit(){ this.subscription = this._authService.getMessage().subscribe(message => { this.user = message; }); }
Welcome component:
ngOnInit() { const checkStatus = this._authService.checkUserStatus(); this._authService.sendMessage(checkStatus); }
Html application component: (error occurs here)
<div *ngIf="user"><div>
What am I trying to do:
I want each component (with the exception of the root application component) to send the registered user state to the root application component, so I can manipulate the user interface in the component component of the root application.
Problem:
I get the following error when the Welcome component is initialized.
Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'true'.
Note that this error occurs in this expression *ngIf="user" , which is located in the HTML file of the root application components.
Can someone explain the cause of this error and how can I fix it?
On the side of the note: If you think that the best way to achieve what I am trying to do, please let me know.
Update 1:
Entering the following into the constructor solves the problem, but does not want to use the constructor for this purpose, so it seems that this is not a good solution.
Welcome component:
constructor(private _authService: AuthenticationService) { const checkStatus = this._authService.checkUserStatus(); this._authService.sendMessage(checkStatus); }
Root Application Component:
constructor(private _authService: AuthenticationService){ this.subscription = this._authService.getMessage().subscribe(message => { this.usr = message; }); }
Update 2:
Here is the plunkr . To see the error, check your browser console. When the application loads a boolean true should be displayed, but I get an error in the console.
Please note that this plunkr is a very simple version of my main application. Since the application is a bit large, I was not able to download all the code. But plunkr demonstrates a mistake perfectly.