【问题标题】:can two injectable (service.ts) communicate with each other in angular 4?两个可注入(service.ts)可以在角度 4 中相互通信吗?
【发布时间】:2017-11-15 05:18:10
【问题描述】:

两个可注入的services.ts文件是否可以相互通信,例如,一个服务是否可以调用另一个服务文件的函数或方法。 如果是,那么这怎么可能,但原因是什么?

【问题讨论】:

    标签: angular typescript ecmascript-6 angular2-services angular-components


    【解决方案1】:

    两个服务可以使用“Injector”类相互通信。

    import { Injectable, Injector } from '@angular/core';
    import { MyService } from 'app/services/my.service';
    

    在构造函数中注入“Injector”对象

    constructor(private injector: Injector) {}
    

    然后调用你的服务

    var myService = this.injector.get(MyService);
    myService.get();
    

    【讨论】:

    • 你能解释一下这个概念吗?为什么它与服务与组件通信时不同
    • 由于循环依赖,您不能将一项服务直接引用到另一项服务中。
    • 你能解释一下这行吗……我的意思是为什么这件事……为什么我们不能直接使用 this.injector.get() var myService = this.injector.get(MyService);
    【解决方案2】:

    您似乎不能让两个服务通过相互构造函数注入相互引用,例如

    @Injectable()
    export class Service1 {
      constructor(private service2: Service2) {}
      method1() {
        ...
      }
    }
    
    @Injectable()
    export class Service2 {
      constructor(private service1: Service2) {}
      method2() {
        ...
      }
    }
    

    当你使用构造函数参数注入时,你会得到这个错误

    compiler.es5.js:1689 Uncaught Error: Can't resolve all parameters for MyService1: (?).
    at syntaxError (compiler.es5.js:1689)
    


    但是,如果两者都使用构造函数之外的注入器,则可以完成

    @Injectable()
    export class Service1 {
      constructor(private injector: Injector) {}
    
      method1() {
        return 'some value';
      }
    
      method1a() {
        const service2 = this.injector(Service2);
        service2.method2()
      }
    }
    
    @Injectable()
    export class Service2 {
      constructor(private injector: Injector) {}
    
      method2() {
        return 'another value';
      }
    
      method2a() {
        const service1 = this.injector(Service1);
        service1.method1()
      }
    }
    

    注意,我会非常小心,不要调用然后回调同一个服务的方法,例如

    Service1.method1 calls Service2.method2
    which then calls Service1.method1
    which then calls Service2.method2
    ...
    

    在处理复杂的逻辑时,这可能很难避免。

    最好的方法是将其中一个服务拆分为两个独立的服务,这样它们就不需要互相调用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 2013-08-18
      相关资源
      最近更新 更多