开始首次呼叫IntervalObservable瞬间 [英] Start first call of IntervalObservable instant
问题描述
我正在使用IntervalObservable
连续调用应用程序的服务器端.我可以订阅和取消订阅Oberservable,并且一切正常,但有一个例外:
I'm using an IntervalObservable
to make continuous calls to the server side of my application. I can subscribe and unsubscribe to to the Oberservable and everything works fine with one exception:
对服务器的第一次呼叫被延迟,但是我希望它是即时的. IntervalObservable
的行为原则上是正确的,但不符合我的要求.
The first call to the server is delayed, but I want it to be instant. The behaviour of the IntervalObservable
is in principle correct, but does not match my requirements.
@Injectable()
export class LoggerService {
constructor(private http: Http) { }
private apiURL = 'assets/file.json';
getList() {
return IntervalObservable.create(1000).flatMap(()
=> this.http.get(this.apiURL))
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
var fooot = new Foo();
fooot.fillFromJSON(JSON.stringify(res.json()));
return fooot;
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return IntervalObservable.throw(errMsg);
}
}
那么我如何在首次调用后立即以定义的延迟调用服务器?
So how can I call the server instant on the first call and afterwards with the defined delay?
推荐答案
两件事,
- 您可以使用工厂方法代替派生类型,即使用
Observable.interval(3000)
代替IntervalObservable.create
-
您可以使用
timer
来代替一个运算符:
- You can use the factory methods instead of the derived types, i.e.
Observable.interval(3000)
instead ofIntervalObservable.create
You can use
timer
to do it with a single operator instead:
return Observable.timer(0, 1000)
.flatMapTo(this.http.get(this.apiURL))
.map(this.extractData)
.catch(this.handleError);
这篇关于开始首次呼叫IntervalObservable瞬间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!