簡體   English   中英

RXJS-IntervalObservable與.startWith

[英]RXJS - IntervalObservable with .startWith

我已經在Angular應用程序中使用IntervalObservable和startWith實現了http池化以立即啟動。 我想知道IntervalObservable是否會等到初始/上一個調用完成流數據處理之后? 是否有更好的方法在Angular應用中實現數據池化。

來自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);
}

來自component.ts的示例

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

}

我已經使用了Angular httClient,但我希望這沒有關系。

以下內容可能會對您有所幫助:

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

您的代碼對我來說似乎很合理。 這是一個類似的代碼,使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM