I am working on an Angular2 app where the user can regsiter and log in. To handle the session - for the purpose of this discussion this mean only a flag if the user if logged in or not - I created a Service which 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 UI elements / menu items. Question is simply: how can I use one central instance of this service throughout my whole 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 on 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 are: - In the console I see the output "New SessionService" twice (see constructor of SessionService) - When I trigger the method this._sessionService.logOut() in the LoginComponent all elements bound to _sessionService.isLoggedIn() of the template of LoginComponent disappear/appear, but for other bound elements in the App template, nothing changes.
Do I have a basic misunderstanding of Angular2 here? Is this approach reasonable? If no, what would be an alternative?
Thanks a lot!
PS: I hope the amount of code is not too much...
Your problem is in your LoginComponent
. Don't put the SessionService
in the providers
array. This creates a second instance.
Put the SessionService
in the providers of the parent component that is common to all of the components that will use the service. This will make it available to all of its child components. In this case, just the AppComponent
.
Then, you can just put the SessionService
in the constructor of each child component that will use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With