/app
- app.component.ts
- app.component.html (hide/show: menu bar)
- app.global.service.ts (Public varible LoginSuccess:boolean)
- m
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:
You should have an app.component.ts
and instead of boostrapping inside of app.module.ts
you inject the service into app.component.ts
.
...
import { MusicService } from './Services/music-service';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
providers: [MusicService],
...
})
export class AppComponent {
constructor(private MS: MusicService) {
}
...
This is based off the current Angular2
build. So inside index.html
you should have <app-root>
where AppComponent
is loaded.
Now to use it inside any other component use just import it:
import { MusicService } from './Services/music-service';
and initialize it:
constructor(private MS: MusicService) {
}
Summary:
app.component.ts
app.component.ts
as a provider
Reference: Angular Dependency Injection
As of final release (Angular 2.0.0) :
Import the service and inject it in the providers array like so :
import { GlobalService } from './app.global.service';
//further down:
@NgModule({
bootstrap: [ App ],
declarations: [
// Your components should go here
],
imports: [
// Your module imports should go here
],
providers: [
ENV_PROVIDERS // By Angular
// Your providers should go here, i.e.
GlobalService
]
});
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 provide GlobalService
at bootstrap, and not for each component:
bootstrap(AppComponent, [GlobalService])
@Component({
providers: [], // yes
// providers: [GlobalService], // NO.
})
class AppComponent {
constructor(private gs: GlobalService) {
// gs is instance of GlobalService created at bootstrap
}
}
This way GlobalService
will be a singleton.
For more advanced approach see this answer.