Angular 2 中有没有办法在服务之间传递数据?

Is there a way in Angular 2 to pass data betwen services?

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

服务 1

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

Service2 类似

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

我认为这比真正的解决方案更 "hack" 但注入第三个服务不起作用。

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

有线索吗?

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

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

另见

您还可以使用 observables,以便一个服务可以订阅另一个服务的变化。