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



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

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

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

在构造函数中注入"注入器"对象

constructor(private injector: Injector) {}

然后致电您的服务

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

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

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

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

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

最新更新