使用Angular 6中的subscribe在间隔中调用和等待

问题描述 投票:3回答:2

我每10000次调用一个方法。我想让这个函数getAllNotificationsActed0()每10秒调用一次,如果数据没有在这个间隔内,请不要再次调用该函数。如果在10秒内收到数据,则调用该函数,如果数据未在函数的10秒内到达,则不要调用,而是等待。

service.ts

public NotifGetAllActedNoActive(): Observable<Notifications[]> {
  let headers = new Headers();
  headers.append('x-access-token', this.auth.getCurrentUser().token);
  return this.http.get(Api.getUrl(Api.URLS.NotifGetAllActedNoActive), {
    headers: headers
  })
    .map((response: Response) => {
      let res = response.json();
      if (res.StatusCode === 1) {
        this.auth.logout();
      } else {
        return res.StatusDescription.map(notiff => {
          return new Notifications(notiff);
        });
      }
    });
}

component.ts

ngOnInit() {
  this.subscription = Observable.interval(10000).subscribe(x => {
    this.getAllNotificationsActed0();
  });
}

getAllNotificationsActed0() {
  this.notif.NotifGetAllActedNoActive().subscribe(notification0 => {
    this.notification0 = notification0;
    if (this.isSortedByDate) {
      this.sortbydate();
    }
  });
}

有什么好主意吗?

angular typescript subscription
2个回答
2
投票

在您的组件中尝试此操作:

import { takeUntil } from 'rxjs/operators';
import { Subject, timer } from 'rxjs';

private _destroy$ = new Subject();
ngOnInit() {
    this.getAllNotificationsActed0();
}
ngOnDestroy() {
    this._destroy$.next();
}
getAllNotificationsActed0() {
    this.notif.NotifGetAllActedNoActive()
     .pipe(takeUntil(this._destroy$))
     .subscribe(notification0 => {
        this.notification0 = notification0;
        if (this.isSortedByDate) {
            this.sortbydate();
        }
        timer(10000).pipe(takeUntil(this._destroy$))
            .subscribe(t => this.getAllNotificationsActed0() );
    });
}

这是阻止组件销毁管道的好方法。您可以使用Subject对象来实现此目的。此外,您可以停止任何必须在组件销毁时停止的管道。


0
投票

试试这个

您可以保留一个标志来查找等待请求

//New Flag
requestWaiting : boolean = false;

public NotifGetAllActedNoActive(): Observable<Notifications[]> {
let headers = new Headers();
headers.append('x-access-token', this.auth.getCurrentUser().token);
return this.http.get(Api.getUrl(Api.URLS.NotifGetAllActedNoActive), {
  headers: headers
})
  .map((response: Response) => {
    this.requestWaiting = false;
    let res = response.json();
    if (res.StatusCode === 1) {
      this.auth.logout();
    } else {
      return res.StatusDescription.map(notiff => {
        return new Notifications(notiff);
      });
    }
 });
}

在区间内调用方法的地方使用标志

ngOnInit() {
  this.subscription = Observable.interval(10000).subscribe(x => {
     if(!this.requestWaiting){
         this.requestWaiting = true;
         this.getAllNotificationsActed0();
     }
  });
}
  getAllNotificationsActed0() {
    this.notif.NotifGetAllActedNoActive().subscribe(notification0 => {
      this.notification0 = notification0;
      if (!this.isSortedByDate) {
        this.sortbydate();
      }
    });
  }

已触发的observable将等到收到响应。我希望它会对你有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.