I have an Oberservable for getting data.
I use a Subscription to call it in an interval in my component.
ngOnInit () {
this.subscr = interval (10000).pipe (
startWith (0),
mergeMap (obs => this.myservice.getData ().pipe (catchError (error =>
{
// error
})))).subscribe (resp =>
{
// data
});
}
ngOnDestroy ()
{
this.subscr.unsubscribe ();
}
I like to have the data refreshed by action (e.g. a button).
refreshNow ()
{
this.myservice.getData ().pipe (catchError (error =>
{
// error
})))).subscribe (resp =>
{
// data
});
}
But I do not like to have getData multiple times in the code. Is there a way I can fire this.subscr manually??
You can use a Subject and combine the both with merge(), something like:
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();
}
May I ask whats the meaning of $ at the end of the variables?
Is just code conventions.
iAmAnObservable$
iAmSomeKindOfSubject$$
. When a variable end with$$
it means it can be used to emit new values. When it end with just one$
it can just be subscribed.