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

Angular2 - How can I retry after an HTTP Request fails and still subscribe to the error?

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

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

这是我的代码:

服务:

@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());
    }
}

组件:

@Component({
  selector: 'app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.less'],
  providers: [CompanyService]
})
export class EeeComponent implements OnInit {
  target: any;
  error: CustomError;

  constructor(
      private route: ActivatedRoute,
  ) {}

  ngOnInit(): void {
      this.route.params
          .switchMap((params: Params) => this.companyService.getCompany(params['id']))
        .subscribe(
            (company) => this.target = company,
            (error) => {
              // Can't reach this !
              this.error = error;
            }
        );
    }
}

实施 Observable.Interval 以每 5 秒发出一次 http 请求。看看这个线程:

我建议将重试逻辑移出 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)
   );
}