Angular 2设置和获取 [英] Angular 2 Setter and Getter

查看:93
本文介绍了Angular 2设置和获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一项服务,以将数据解析为不同路线上的不同组件.

I am attempting to create a service to parse data to different components on different routes.

如果在同一组件上调用Follow服务,则会得到所需的结果,但是,如果尝试从另一个组件获取设置结果,则该服务将返回未定义的结果.

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.

这是我的服务:-

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

我将服务设置为:-

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.

类似这样的东西:

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

这篇关于Angular 2设置和获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆