Angular 2 Setter and Getter

瘦欲@ 提交于 2019-12-03 15:59:35

If you want to share a service across components that are not children of the parent component, you need to register the service in the module, not in the component. When you register a service within a component, it is only available to that component and its children.

Something like this:

@NgModule({
  declarations: [
    AppComponent,
    ProductListComponent,
    StarComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [ TestService ],
  bootstrap: [AppComponent]
})
export class AppModule { }

If you are trying to interact between two components which are from different modules, then you have to import your service into the app module(i.e main module), in this way get method does not return

Try initializing testService var like this code inside of the constructor in your Component.ts tha could work if the undefined var is "testService".

constructor (private testService : TestService ){
      //at this time testService its already initialized.
     console.log(this.testService.test);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!