我有一个Angular应用程序,我试图在其中每隔几秒钟检查一次外部数据服务是否有更改,并更新视图。
我尝试从rxjs实现轮询,但是我无法访问该对象,相反,轮询功能似乎无法正常工作,但认为这是因为返回的对象不可访问。
app.component.ts
export class AppComponent {
polledItems: Observable<Item>;
items : Item[] = [];
title = 'site';
landing = true;
tap = false;
url:string;
Math: any;
getScreen(randomCode) {
const items$: Observable<any> = this.dataService.get_screen(randomCode)
.pipe(tap( () => {
this.landing = false;
this.Math = Math
}
));
const polledItems$ = timer(0, 1000)
.pipe(( () => items$))
console.log(this.polledItems);
console.log(items$);
}
摘自app.component.html
<h3 class="beer-name text-white">{{(polledItems$ | async).item_name}}</h3>
data.service.ts的摘录
get_screen(randomCode) {
return this.httpClient.get(this.apiUrl + '/tap/' + randomCode)
}
答案 0 :(得分:1)
假设您想要一系列类似的物品。
// dont subscribe here but use the
// observable directly or with async pipe
private readonly items$: Observable<Item[]> = this.dataService.get_screen(randomCode)
// do your side effects in rxjs tap()
// better move this to your polledItems$
// observable after the switchMap
.pipe(
tap( () => { return {this.landing = false; this.Math = Math}; })
);
// get new items periodicly
public readonly polledItems$ = timer(0, 1000)
.pipe(
concatMap( () => items$),
tap( items => console.log(items))
)
模板:
// pipe your observable through async and THEN access the member
<ng-container *ngFor="let polledItem of (polledItems$ | async)>
<h3 class="item-name text-white">{{polledItem.item_name}}</h3>
</ng-container>
看看:https://blog.strongbrew.io/rxjs-polling/
如果您不是在等待数组,而是一个数组,则不需要ngFor,但可以像下面这样访问您的item_name:
<h3 class="item-name text-white">{{(polledItems$ | async).item_name}}</h3>