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



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

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

这是我的代码:

服务:

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

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

实现一个 Observable.Interval 来每 5 秒发出一次 http 请求。 看看这个线程: Angular2 http at a interval

最新更新