[英]RXJS - IntervalObservable with .startWith
I have implemented http pooling in Angular app with IntervalObservable and startWith to start instantly. 我已经在Angular应用程序中使用IntervalObservable和startWith实现了http池化以立即启动。 I wanted to know does IntervalObservable wait until initial/previous call finished streaming data?
我想知道IntervalObservable是否会等到初始/上一个调用完成流数据处理之后? Is there a better way to implement data poolingin Angular app.
是否有更好的方法在Angular应用中实现数据池化。
Ex from service.ts 来自service.ts
getRecordsList() {
return IntervalObservable
.create(15000)
.startWith(0)
.flatMap((r) => this.http
.post(`http://services.com/restful/recordService/getRecordsList`, body, {
headers: new HttpHeaders().set('Content-Type', 'application/json')
}))
.shareReplay()
.catch(this.handleError);
}
Ex from component.ts 来自component.ts的示例
ngOnInit() {
this.service.getRecordsList()
.subscribe(
(recordList) => {
this.recordResponse = recordList;
},
error => { console.log },
() => console.log("HTTP Observable getRecordsList() completed...")
);
} }
I have used Angular httClient and I hope this doesn't matter anyhow. 我已经使用了Angular httClient,但我希望这没有关系。
Here's something that might help you: 以下内容可能会对您有所帮助:
const { Observable } = Rx;
// HTTP MOCK
const http = {
post: () => Observable.of('some response').delay(1000)
}
// SERVICE PART
const polling$ = Observable.timer(0, 5000);
const myRequest$ = polling$
.do(() => console.log(`launching a new request...`))
.switchMap(() => http.post('some-url'));
// COMPONENT PART
myRequest$
.do(res => console.log(`Response: ${res}`))
.subscribe();
And a working Plunkr: https://plnkr.co/edit/BCTmlOv6FarNN1iUmMcA?p=preview 和一个工作的Plunkr: https ://plnkr.co/edit/BCTmlOv6FarNN1iUmMcA ? p = preview
Your code seems reasonable to me. 您的代码对我来说似乎很合理。 Here is a similar code that uses
IntervalObservable
to pool the server until some condition is met. 这是一个类似的代码,使用
IntervalObservable
来缓冲服务器直到满足某些条件。
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { IntervalObservable } from 'rxjs/observable/IntervalObservable';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/operator/startWith';
@Component({
selector: 'my-angular2-app',
templateUrl: './tool-component.html',
styleUrls: ['./tool-component.css']
})
export class ToolComponent {
private _APIBaseURL = 'https://api.app.io';
private _autoRefresh: boolean = true;
private _downloadLink: string = ""
private _fileID: string = ""
constructor(private _http: Http) { }
// add code here
// ...
getDownloadLink() {
this._autoRefresh = true;
this._downloadLink = "";
IntervalObservable
.create(10000)
.startWith(0)
.takeWhile(() => this._autoRefresh)
.subscribe(() => {
this._http.get(`${this._APIBaseURL}/rocess?file-name=${this._fileID}`)
.subscribe(data => {
let idata = data.json();
if (idata['current_status'] == "done") {
this._downloadLink = idata.url;
this._autoRefresh = false;
}
})
}
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.