RXJS - 带.startWith的IntervalObservable

时间:2017-10-03 22:33:14

标签: angular rxjs angular-httpclient

我已经在Angular应用程序中使用IntervalObservable和startWith实现了http池,以便立即启动。我想知道IntervalObservable是否等到初始/上一次调用完成流数据? 是否有更好的方法在Angular app中实现数据池。

Ex from 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

ngOnInit() {
 this.service.getRecordsList()
  .subscribe(
    (recordList) =>  {
      this.recordResponse = recordList;          
    },
    error => { console.log },
    () => console.log("HTTP Observable getRecordsList() completed...")
);

}

我使用过Angular httClient,我希望无论如何这并不重要。

2 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助:

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

一个正在使用的Plunkr:https://plnkr.co/edit/BCTmlOv6FarNN1iUmMcA?p=preview

答案 1 :(得分:0)

您的代码对我来说似乎很合理。下面是一个类似的代码,它使用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;
                        }
                    })
            }
            )
    }
}