Javascript Angular6轮询不返回数据
我有一个Angular应用程序,尝试每隔几秒钟检查外部数据服务的更改,并更新视图 我尝试从rxjs实现轮询,但无法访问对象,相反,轮询函数似乎不起作用,但假设这是因为返回的对象不可访问 app.component.tsJavascript Angular6轮询不返回数据,javascript,angular,rest,rxjs,polling,Javascript,Angular,Rest,Rxjs,Polling,我有一个Angular应用程序,尝试每隔几秒钟检查外部数据服务的更改,并更新视图 我尝试从rxjs实现轮询,但无法访问对象,相反,轮询函数似乎不起作用,但假设这是因为返回的对象不可访问 app.component.ts export class AppComponent { polledItems: Observable<Item>; items : Item[] = []; title = 'site'; landing = true; tap = false;
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$);
}
假设您需要一组项目,您可以使用类似的东西
// 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>
看看:
如果您正在等待的不是阵列而是单个,则不需要ngFor,而是访问您的项目名称,如:
<h3 class="item-name text-white">{{(polledItems$ | async).item_name}}</h3>
我已经更新了帖子,但是基本上收到了和以前一样的数据,我只是可以观察到{..在我的控制台中。抱歉,我错过了第二个可观察对象中的concatMap。allso将可观察对象添加为类成员不需要重新创建它们。polledItems应为可观察类型。控制台日志需要位于可观察对象内,否则数据到达时不会记录。导出类AppComponent{polledItems:Observable;..private readonly items$:Observable=..public readonly polledItems$=timer0,1000.pipe concatMap=>this.items$,点击polledItems=>console.logpolledItems;}
// 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>
<h3 class="item-name text-white">{{(polledItems$ | async).item_name}}</h3>