Angular – 通过 Observables 实现服务间的通信

huangapple go评论60阅读模式
英文:

Angular - communication between services with observables

问题

Subscribe the observable in bServiceMethod and use take(1)?

英文:

I have a service with a method where I emit an observable, then in another service I want to subscribe to that observable, what's the best way to do this?

aServiceMethod(value){
      this.serviceA.obs$.next(value);
}

bServiceMethod(){
    let method B = //get value from obs
}

Subscribe the observable in bServiceMethod and use take(1)?

Subscribe the observable in the constructor of service B?

Transform the observable into behaviorSubject and use getValue()?

Other?

答案1

得分: 1

我认为在这里使用 BehaviorSubject 是跟踪全局感兴趣的值的最佳策略(在不同服务之间)。

aServiceMethod 方法中发出值,如下所示:

export class ServiceA {
  obs$ = new BehaviorSubject<any>(null);

  aServiceMethod(value: any){
    this.obs$.next(value);
  }
}

并在 bServiceMethod 中订阅可观察对象:

export class ServiceB {
  constructor(private serviceA: ServiceA) {
    this.bServiceMethod();
  }

  bServiceMethod() {
    this.serviceA.obs$.subscribe(value => {
      let methodB = value;
      console.log(methodB);
    });
  }
}
英文:

I think using a BehaviorSubject here would be the best strategy to keep track of the value of interest globally (between the different services)

Emitting the value from the aServiceMethod method, in the tune of:

export class ServiceA {
  obs$ = new BehaviorSubject&lt;any&gt;(null);

  aServiceMethod(value: any){
    this.obs$.next(value);
  }
}

and subscribing to the observable in bServiceMethod:

export class ServiceB {
  constructor(private serviceA: ServiceA) {
    this.bServiceMethod();
  }

  bServiceMethod() {
    this.serviceA.obs$.subscribe(value =&gt; {
      let methodB = value;
      console.log(methodB);
    });
  }
}

huangapple
  • 本文由 发表于 2023年7月10日 15:55:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651747-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定