我有一个Oberservable来获取数据。
我使用Subscription在组件中的某个间隔中对其进行调用。
ngOnInit(){
this.subscr = interval (10000).pipe (
startWith (0),
mergeMap (obs => this.myservice.getData ().pipe (catchError (error =>
{
// error
})))).subscribe (resp =>
{
// data
});
}
ngOnDestroy ()
{
this.subscr.unsubscribe ();
}
我喜欢通过操作(例如按钮)刷新数据。
refreshNow ()
{
this.myservice.getData ().pipe (catchError (error =>
{
// error
})))).subscribe (resp =>
{
// data
});
}
但是我不喜欢在代码中多次使用getData。有什么方法可以手动触发this.subscr吗?
你可以使用Subject并将二者与merge()结合使用,例如:
private readonly triggerRefresh$$ = new Subject<void>();
// ....
this.subscr = merge(interval(10000), this.triggerRefresh$$)
.pipe (
switchMapTo(this.myservice.getData ()
.pipe(catchError (error => {}))
)
).subscribe (resp => {
// data
});
refreshNow () {
this.triggerRefresh$$.next();
}
请问变量末尾$的含义是什么?
仅仅是代码约定。
iAmAnObservable$
iAmSomeKindOfSubject$$
。当变量以$$
它结尾时,它可以用来发出新值。当它仅以一个结尾时,$
就可以订阅它。