Looks like shared services is the best practice to solve many situations such as communication among components or as replacement of the old $rootscope concept of angular 1.
Most of time, you need to define your shared service when bootstrapping your application:
bootstrap(AppComponent, [ SharedService ]);
and not defining it again within the providers
attribute of your components. This way you will have a single instance of the service for the whole application.
In your case, since OtherComponent
is a sub component of your AppComponent
one, simply remove the providers
attribute like this:
@Component({
selector : "other",
// providers : [SharedService], <----
template : `
I'm the other component. The shared data is: {{data}}
`,
})
export class OtherComponent implements OnInit{
(...)
}
This way they will shared the same instance of the service for both components. OtherComponent
will use the one from the parent component (AppComponent
).
This is because of the "hierarchical injectors" feature of Angular2. For more details, see this question:
In addition to your requirement and its solution, you can consider using Facade + Shared Services. I have a small project here: https://github.com/cmandamiento/angular-architecture-base
You need to add a global provider in your module, then you dont need to add this provider in each component. try this
app.module.ts
@NgModule({
imports: [BrowserModule, FormsModule, HttpModule],
declarations: [AppComponent, LoginComponent, InComponent],
providers: [LoginService],
bootstrap: [AppComponent]
})
app.component.ts
@Component({
moduleId: module.id,
selector: 'app',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(public loginService: LoginService) {
}
}
login.component.ts
@Component({
moduleId: module.id,
selector: 'login',
templateUrl: './login.component.html'
})
export class LoginComponent {
constructor(public loginService: LoginService) {
}
}
I hope this work for you.