angular - 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.
解决方案
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.
推荐阅读
- gethashcode - 通过从对象返回唯一 ID 来实现 GetHashCode 是否安全?
- .net-core - csharp 中是否有类似 Rust 的 std::option_env 的东西?
- dll - 如何从基于 Chromium 的应用程序调用 c++ DLL
- pandas - pandas:基于另一个数据帧中的映射对特定列进行分组和求和
- python - 是否可以使用 powershell 运行 base64 编码的二进制文件
- wpf - 我可以启用 GPU 可视化吗?(在 WPF 中)
- javascript - Javascript 在第一个条件失败时停止,需要将其移至第二个条件
- nginx - NGINX Certbot 配置不起作用。但是代理通行证适用于一个服务在另一个配置中工作
- typescript - 在打字稿中将整数值转换为字符串枚举返回未定义
- jenkins - 詹金斯:使用参数构建按钮不断消失