0

我已经在 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,我希望无论如何这都无关紧要。

4

2 回答 2

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;
                        }
                    })
            }
            )
    }
}
于 2017-10-13T19:58:33.370 回答
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

于 2017-10-04T06:47:12.267 回答