可以两个注射(service.ts)以角度4相互通信吗?

时间:2017-11-15 05:18:11

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

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

2 个答案:

答案 0 :(得分:0)

两个服务可以使用“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();

答案 1 :(得分:0)

看来你不能有两个服务通过相互构造函数注入相互引用,例如

@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
...

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

最好的方法是将其中一项服务拆分为两个独立的服务,这样他们就不需要互相打电话了。