I am working on an Angular2 application where a user can register and log in. For session processing - for the purposes of this discussion, this only means a flag if the user, if he has registered or not, has created a service that looks like this:
import {Injectable} from 'angular2/core'; @Injectable() export class SessionService { private _status:boolean; constructor () { if(1 == 1) { this._status = true; } console.log("New SessionService"); } isLoggedIn() { return this._status; } logOut() { this._status = !this._status; } }
Now I want to use the isLoggedIn () method in my template to show or hide certain user interface elements / menu items. The question is simple: how can I use one central instance of this service throughout my application?
I tried something like this for my AppComponent:
(...) import {SessionService} from '../services/session.service'; @Component({ selector: 'my-app', templateUrl: 'app/app/app.component.html', directives: [ROUTER_DIRECTIVES], providers: [SessionService] }) @RouteConfig([ ... ]) export class AppComponent { constructor(private _userService: UserService, private _sessionService: SessionService) {} }
And basically the same for the other (child) component:
(...) import {SessionService} from '../services/session.service'; @Component({ templateUrl: 'app/user/login.component.html', directives: [ROUTER_DIRECTIVES], providers: [HTTP_PROVIDERS, UserService, SessionService] }) export class LoginComponent { model = {email: "", password: ""} constructor(private _userService: UserService, private _sessionService: SessionService) {} onSubmit() { this._sessionService.logOut(); } }
My observations with this: - In the console, I see the result "New service session" twice (see SessionService Constructor) - When I call the this._sessionService.logOut () method in LoginComponent, all the elements attached to the _sessionService.isLoggedIn () template of the LoginComponent disappear / appear, but for other related elements in the application template, nothing changes.
Do I have a basic misunderstanding of Angular2 here? Is this approach reasonable? If not, what is the alternative?
Thanks a lot!
PS: I hope the amount of code is not too much ...