【发布时间】:2017-03-21 09:17:49
【问题描述】:
由于我是 Angular 新手,我想知道实现我想要的最佳实践应该是什么。
我想请求一个 API,直到我得到我想要的结果以及请求之间的间隔。
我使用两个嵌套服务(GiftsService 和 ApiService):
gifts.service.ts:
import { Injectable } from '@angular/core';
import { URLSearchParams } from '@angular/http';
import { environment } from '../../../environments/environment';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { ApiService } from './api.service';
import { Gift } from '../models';
@Injectable()
export class GiftsService {
constructor (
private apiService: ApiService
) {}
get(id): Observable<Gift> {
return this.apiService.get('/gifts/' + id)
.map(data => data);
}
...
api.service.ts
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { Headers, Http, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';
@Injectable()
export class ApiService {
constructor(
private http: Http,
private jwtService: JwtService
) {}
get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
return this.http.get(path, { headers: this.setHeaders(), search: params })
.catch(this.formatErrors)
.map((res:Response) => res.json());
}
...
我在这样的组件中调用 GiftsService.get :
this.giftsService.get(this.gift.id)
.subscribe(data => {
// if data.status != "ok" retry
})
更新
我是怎么做到的
this.giftsService.get(this.gift.id)
.switchMap(data => data.status !== 'success' ? Observable.throw(new Error('status not successful')) : Observable.of(data))
.retryWhen(attempts => {
return Observable
.range(1,10)
.zip(attempts, function(i) {
return(i);
})
.flatMap(function(i) {
return Observable.timer(1000);
})
})
.subscribe((
data => {
this.gift = data
})
);
【问题讨论】:
-
In Error function retry to hit the service 例如 this.giftsService.get(this.gift.id) .subscribe(data => { // if data.status != "ok" retry,错误 => 调用服务...... = 错误 })
-
你可以像这样使用 rxjs retrywhen 操作符:stackoverflow.com/questions/40175255/…