typescript Angular 2 Setter 和 Getter
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44890518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 Setter and Getter
提问by Tony Hensler
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.
如果您需要任何额外的代码,请告诉我。
回答by DeborahK
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 { }
回答by arun kumar
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
如果您尝试在来自不同模块的两个组件之间进行交互,那么您必须将您的服务导入应用程序模块(即主模块),这样 get 方法不会返回
回答by Abel Valdez
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);
}