In my Angular 2 application (beta 14), I need to track user login status in order to hide / show some elements.
The problem I am getting is that property binding does not work the way I did the following.
I created a class to store and update global variables:
application-global.ts
import {Injectable} from "angular2/core"; @Injectable() export class AppGlobals {
In the login component, I import AppGlobals
export class LoginComponent { constructor(private _appGlobals: AppGlobals) { }
and set the input state
this._appGlobals.setLoginStatus (true);
In another component, I add AppGlobals, as in LoginComponent
I am defining a class (component) property
isLoggedIn: boolean = this._appGlobals.isUserLoggedIn; // I also tried using getter instead of a public property (see above)
which I then use in the component template to show / hide a specific element:
<div id="some-element" [hidden] = "!isLoggedIn">
Finally, the binding works, but there is no update (this component is part of the AppComponent template and shown on each page) when another component (for example, LoginComponent) sets the login status.
EDIT I tried applying the Gunter answer, but I get the following errors:
app/app-globals.ts(10,54): error TS2346: Supplied parameters do not match any signature of call target. app/app-globals.ts(13,29): error TS2339: Property 'emit' does not exist on type 'BehaviorSubject<boolean>'.
The error in line 10 comes from [SOLVED]
public isUserLoggedIn: BehaviorSubject = new BehaviorSubject (). startWith (false);
and this is apparently due to BehaviorSubject expecting parameter 1
The error on line 13 comes from
this.isUserLoggedIn.emit (isLoggedIn);
and this apparently calls the non-existent emit method.
Also, I don’t understand how to use AppGlobals so that the property binds automatic updates to another component (see the last example before EDIT)
Also, in LoginComponent, I replaced the boolean type isLoggedIn with BehaviorSubject , because isUserLoggedIn is of type BehaviorSubject in AppGlobals
but
this._appGlobals.isUserLoggedIn.subscribe (value => this.isLoggedIn = value);
returns TypeError:
The assigned boolean expression type is not assigned to the BehaviorSubject type