Angular2: centralized session service?

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 ...

+5
source share
1 answer

Your problem is in your LoginComponent . Do not put the SessionService in the providers array. This creates a second instance.

Put the SessionService in the providers of the parent component, which is common to all components that will use this service. This will make it accessible to all of its child components. In this case, just an AppComponent .

Then you can simply put the SessionService in the constructor of each child component that will use it.

+8
source

Source: https://habr.com/ru/post/1246264/


All Articles