英文:
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<any>(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 => {
let methodB = value;
console.log(methodB);
});
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论