/app
- app.component.ts
- app.component.html (hide/show: menu bar)
- app.global.service.ts (Public varible LoginSuccess:boolean)
- main.ts
/student
- student.ts
- student.service.ts
- student.component.ts
- student.component.html
/security
- login.component.ts (LoginSuccess = true)
- login.component.html
In my application of Angular2, I have a simple need where I want to show hide menu bar based on login success. For that I created a service which just have a LoginSuccess boolean varilable, which I would set on login component and will use on app.component.html for [hidden]=LoginSuccess
nav tag.
Problem I am facing is, even after injecting app.global.service.ts
thru constructor
of app.component.ts & login.component.ts
value is not persisting and each constructor creating new object of app.global.service.ts
.
Question: How can I achieve to persist single value across application thru service. Somewhere in Angular2 docs, I did read that Injectable service is singleton.
I will just add, because i was stuck at this point to, although i used a Singelton, you also have to use the Angular routing strategie:
You can't use href="../my-route"
cause this starts the whole application new:
instead you have to use: routerLink="../my-route"
You should have an
app.component.ts
and instead of boostrapping inside ofapp.module.ts
you inject the service intoapp.component.ts
.This is based off the current
Angular2
build. So insideindex.html
you should have<app-root>
whereAppComponent
is loaded.Now to use it inside any other component use just import it:
and initialize it:
Summary:
app.component.ts
app.component.ts
as aprovider
Reference: Angular Dependency Injection
You should provide
GlobalService
at bootstrap, and not for each component:This way
GlobalService
will be a singleton.For more advanced approach see this answer.
As of final release (Angular 2.0.0) :
Import the service and inject it in the providers array like so :
As Saxsa, the key point is to define your service provider within the application injector and not at each component level. Be careful not to define the service provider twice... Otherwise you will still have separate service instances.
This way you will be able to share the same instance of the service.
This behavior occurs because of hierarchical injectors of Angular2. For more details, you could have a look at this question:
Beginning with Angular 6.0, the preferred way to create a singleton services is to specify on the service that it should be provided in the application root. This is done by setting
providedIn
toroot
on the service's@Injectable
decorator: