Angular2 - 如何在HTTP请求失败后重试并仍然订阅错误?

时间:2017-08-03 21:33:47

标签: angular httprequest rxjs observable polling

我正在建立一个假设要触发http.get请求和重新触发的应用程序  如果发生错误,请求每5秒一次。但是,我需要能够在重新触发请求时在屏幕上显示此错误。

我没有找到rxjs重试/重试的任何解决方案因为他们只是在重新触发之前拦截错误,我无法订阅错误。

这是我的代码:

服务:

php bin/cake.php server...

组件:

@Injectable()
export class CompanyService extends WabelService {
    constructor (private http: Http) {
      super();
      this.service_uri = "company";
    }

    getCompany(id: string): Observable<Company> {
        return this.http.get(this.url+"/"+id)
            .retry()
            .map(response => response.json());
    }
}

2 个答案:

答案 0 :(得分:2)

我建议将重试逻辑移出companyService

ngOnInit(): void {
  this.route.params
   .switchMap(({id}) => 
     this.companyService.companyService.getCompany(id)

       // Handle the retry logic here instead so you have access to this.error
       .retryWhen(e => 

         // Set the error when you receive one
         e.do({
           error: err => this.error = err
         })

         // Delay each error by 5 seconds before emitting for a retry
          .delayTime(5000)

         // Optionally stop trying after a while
         .take(10)
       )

       // If you get out here then the error has been dealt with
       // and you can disable your error state
       .do(_ => this.error = null)
   )
   .subscribe(
     company => this.target = company,
     fatalError => console.error('Something really bad happened', fatalError)
   );
}

答案 1 :(得分:-2)

实现Observable.Interval以每5秒发出一次http请求。看看这个主题:Angular2 http at an interval