简体   繁体   English

Angular6轮询不返回数据

[英]Angular6 polling not returning data

I have an Angular application where I am trying to check an external data service for changes every few seconds, and update the view. 我有一个Angular应用程序,该应用程序试图每隔几秒钟检查一次外部数据服务的更改,并更新视图。

I've tried to implement Polling from rxjs but I'm not able to access the object, conversely it seems the polling function isn't working but assume this is because the returned object is inaccessible. 我尝试从rxjs实现轮询,但是我无法访问该对象,相反,轮询功能似乎无法正常工作,但假定这是因为返回的对象不可访问。

app.component.ts 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$);
  }

excerpt from app.component.html 摘自app.component.html

<h3 class="beer-name text-white">{{(polledItems$ | async).item_name}}</h3>

excerpt from data.service.ts 摘自data.service.ts

   get_screen(randomCode) { 
    return this.httpClient.get(this.apiUrl + '/tap/' + randomCode)
   }

assuming that you want an array of items you could go with something like this. 假设您想要一系列物品,则可以使用类似的东西。

// 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))
   )

the template: 模板:

// 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>

take a look at: https://blog.strongbrew.io/rxjs-polling/ 看看: https//blog.strongbrew.io/rxjs-polling/

if you are not awaiting an array but a single than you dont need the ngFor but access your item_name like: 如果您不是在等待数组,而是一个数组,则不需要ngFor,但可以像下面这样访问您的item_name:

<h3 class="item-name text-white">{{(polledItems$ | async).item_name}}</h3>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM