2

Using Angular 7 how to call function immediately and every X seconds? This is my function in service: (just as an example)

checkData(): Observable<string> {
    return this.http.get('')
        .pipe(
            map(res => {
                let result;
                result = {
                    packageNumber: this.packageNumber,
                };
                return result;
            })
        );
}

And in my component I tried something like this:

private killTrigger: Subject<void> = new Subject();
private fetchData$: Observable<string> = this.packageService.checkData();

private refreshInterval$: Observable<string> = timer(0, 1000)
    .pipe(
        takeUntil(this.killTrigger),
        switchMap(() => this.fetchData$),
        catchError(error => of('Error'))
    );

How to make it work?

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83

1 Answers1

0

You need to subscribe to it to launch it. Best way is to:

// class def
private subscription: Subscription;
// in NgOnInit
this.subscription = this.refreshInterval$.subscribe(noop)
// in NgOnDestroy
this.subscription.unsubscribe(); // avoid memory leaks

And to actually fire your fetchData$, you can replace your switchMap call by:

map(() => this.fetchData$.subscribe(noop),

If you don't subscribe to the observable, it never gets fired. Don't see why you would need switchMap here.

Qortex
  • 7,087
  • 3
  • 42
  • 59