我是rxjs的新手,只是想知道通过管道流并点击它来设置类属性是可以的,或者它应该在订阅中进行。对我来说无论哪种方式都有效,只是想知道是否可以按照我认为合适的方式做到这一点,或者有一些我不知道的事情。
打字稿代码演示两种方式:
export class ViewComponent implements OnInit {
applicant = {};
constructor(public route: ActivatedRoute, private store: Store<any>) {}
ngOnInit() {
this.route.paramMap.pipe(
switchMap(params => this.store.select(state => state.applicants.entities[params.get('id')])),
tap(applicant => this.applicant = applicant)
).subscribe();
}
}
VS
export class ViewComponent implements OnInit {
applicant = {};
constructor(public route: ActivatedRoute, private store: Store<any>) {}
ngOnInit() {
this.route.paramMap.pipe(
switchMap(params => this.store.select(state => state.applicants.entities[params.get('id')]))
).subscribe(applicant => this.applicant = applicant);
}
}
好问题。在source code运营商的tap
中,这个评论几乎总结了一下:
此运算符可用于调试Observables以获取正确的值或执行其他副作用。 注意:这与Observable上的
subscribe
不同。如果没有订阅do
返回的Observable,Observer指定的副作用将永远不会发生。因此do
只是监视现有的执行,它不会像subscribe
那样触发执行。
您可以在tap
中运行的任何副作用也可能放在subscribe
区块中。 subscribe
表示你主动使用源值的意图,因为它说“当这个观察值发出时,我想在applicants
变量中保存它的值”。 tap
操作符主要用于调试,但它可用于运行副作用。
一般来说,有利于subscribe
块运行副作用,使用tap
进行调试,但要注意tap
可以做更多,如果你需要它。
当您的观察者与其订阅者分开时,tap
非常有用。如果你有一个公开observable的类,你可以使用tap
来实现当有人正在监听observable时需要执行这个类的副作用。另一方面,当您从另一个类订阅它时,您可以使用subscribe
从订阅者的角度实现副作用。
具有可观察性的类:
public dummyObservable: Observable<number> = from([1, 2, 3, 4, 5]).pipe(
// Side effects, executed every time I emit a value
// I don't know which side effects implements who subscribes to me
tap( n => console.log("I'm emitting this value:", n) )
);
订阅类:
ngOnInit(): void {
this.dummyService.dummyObservable.subscribe(
// Side effects, executed every time I receive a value
// I don't know which side effects implements the observable
data => console.log("I'm receiving this value: ", data)
);
}