简体   繁体   English

Angular 2 Setter和Getter

[英]Angular 2 Setter and Getter

I am attempting to create a service to parse data to different components on different routes. 我正在尝试创建一个服务来将数据解析到不同路由上的不同组件。

If I call the follow service on the same component I get the result I require, but if I try to get the set results from another component the service returns undefined. 如果我在同一个组件上调用follow服务,我会得到我需要的结果,但如果我尝试从另一个组件获取设置结果,则服务返回undefined。

Here is my service:- 这是我的服务: -

import {Injectable} from '@angular/core';

@Injectable()
export class TestService {

  public _test:any;

  set test(value:any) {
    this._test = value
  }

  get test():any {
    return this._test;
  }
}

I set the service like:- 我设置的服务如下: -

this.testService.test = 3;

and I receive the the service data in my component using the following:- 我使用以下内容在组件中收到服务数据: -

console.log(this.testService.test)

As mention before this works absolutely fine if I am communicating within the same component, I have the same imports, providers and constructor. 如前所述,如果我在同一个组件内进行通信,那么这个工作绝对没问题,我有相同的导入,提供者和构造函数。

Also just a note the components are sibling components 另外,请注意组件是兄弟组件

Would anybody be able to help or point me in the right direction it would be very appreciated. 是否有人能够帮助或指出我正确的方向,我们将非常感激。

If you require any extra code please let me know. 如果您需要任何额外的代码,请告诉我。

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 { }

如果您尝试在来自不同模块的两个组件之间进行交互,那么您必须将服务导入到app模块(即主模块)中,这样get方法就不会返回

Try initializing testService var like this code inside of the constructor in your Component.ts tha could work if the undefined var is "testService" . 尝试在Component.ts中的构造函数内部初始化testService var,如果未定义的var是“testService”,则可以工作。

constructor (private testService : TestService ){
      //at this time testService its already initialized.
     console.log(this.testService.test);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM