【问题标题】:Is there a way in Angular 2 to pass data betwen services?Angular 2 中有没有办法在服务之间传递数据?
【发布时间】:2016-11-30 14:05:38
【问题描述】:

我需要将数据从 Service1 传递到 Service2

服务1

@Injectable()
export class Service1 {
    ...
}

Service2 类似

我发现让 Service1 与 Service 2 通信的唯一方法是使用 window['var'](在 Service1 中设置,在 Service2 中读取)

我认为这更像是一种“破解”而不是真正的解决方案,但注入第三个服务不起作用。

另一种解决方案是使用 localStorage,但对我来说似乎并不理想。

有什么线索吗?

【问题讨论】:

    标签: angular angular2-services


    【解决方案1】:

    您可以将一项服务注入另一项服务

    @Injectable()
    class Service2 {
      // constructor(private service2:Service2) {}
      // cyclic dependencies are not supported
      // therefore only one service can inject the other, 
      // but both directions at the same time causes an exception
    
      someProp:String = 'xxx';
    }
    
    @Injectable()
    class Service1 {
      constructor(private service2:Service2) {
        console.log(service2.someProp);
      }
    }
    

    另见DI with cyclic dependency with custom HTTP and ConfigService

    您还可以使用可观察对象,以便一个服务可以订阅另一个服务中的更改。

    【讨论】:

      猜你喜欢
      • 2021-11-30
      • 2018-12-02
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2017-06-20
      • 2017-10-18
      • 2020-07-23
      相关资源
      最近更新 更多