首页 > 解决方案 > Observables Angular 6

问题描述

This is how I implemented my async observables. It runs the api every 1 minute. However when I called it on the html, its saying Cannot read property 'course' of null. Not sure how to do this.

<div class="col-12 col-md-6 col-lg-3" *ngFor="let course of (courses$ | async).course;">
@Input() courses$: Observable<any>;
private courseSubscription: Subscription
getCourses() {
    this.isLoading=true;
    this.courses$ = Observable.create(observer => {
      setInterval(() => {

        observer.next(this.coursemoduleService.getCourses());
      }, 1000)
    })

    this.courseSubscription = this.courses$.subscribe(
      data => {
        this.courses$ = data;
        // console.log(data);
        this.isLoading=false;
      }, error => {
        // console.log(error);
        this.isLoading=false;
      }
    )
  }

I tried doing this:

<div class="col-12 col-md-6 col-lg-3" *ngFor="let course of (courses$ | async)?.course;">

but it will keep reloading the page literally. It should only reload the api without reloading the page.

标签: angularangular6observable

解决方案


Use rxjs built-in interval() function, which creates an Observable basaed interval. Simple import this: import { interval } from 'rxjs'; version 6+, or older use-case: Observable.interval. Ex:

this.courses$ = interval(1000).pipe(
      switchMap(() => this.coursemoduleService.getCourses()),
      catchError((err) => {
        this.isLoading = false;
        return of(err);
      }),
      tap((data) => this.isLoading = false),
);

And don't reassigne this.courses$ variable, because this varibale holds your Observable. After this your async pipe in template will works.


推荐阅读