【问题标题】:Repeat Request based on data result根据数据结果重复请求
【发布时间】:2018-10-15 12:25:32
【问题描述】:

您好,我是 Angular 新手,我想知道根据结果数据重复 GET 请求的正确方法是什么。

item.service.ts

ScanItems():Observable<any>{
    return this.http.get<any>(url)     
}

item.component.ts

GetScannedItems(){
   this.ScanSubscription = this.itemService.ScanItems()
    .subscribe(
       data => {
         RDate = new Date(data.Date).getTime();
         const NDate = new Date().getTime();
         const Diff = RDate - NDate
         if(Diff > (-300000)){
           console.log('Valid')
         }
         else {
           // Repeat Request Here!!!
         }
       },
       error => console.error(error),
       () => this.ScanSubscription.unsubscribe()
   )
}

【问题讨论】:

标签: angular rxjs


【解决方案1】:

您可以使用重试运算符在服务中执行此操作,而不是在组件中处理。

GetScannedItems(){
   this.ScanSubscription = this.itemService.ScanItems()
    .pipe(
      map(
       data => {
         RDate = new Date(data.Date).getTime();
         const NDate = new Date().getTime();
         const Diff = RDate - NDate
         if(Diff > (-300000)){
           return of(true);
         }
         else {
            return Observable.throw('retry');
           // Repeat Request Here!!!
         }
       }),
       delay(500),
       retry()
   )
}

【讨论】:

  • 不要做假设。我认为 OP 问题有点不同。他在问一种递归方法。重试总是会再次发送相同的请求
  • 根据标题重复请求
  • 已更新。检查它是否有效。否则我们需要使用 flatMap
  • 非常感谢,我已将 return Observable.throw() 更改为 throw()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多