RxJS - Subscriber如何与Observable和Subscription不同?

时间:2017-11-15 05:28:58

标签: angular rxjs

我一直试图找到一个将Observable包装到Subscriber中以监控异步调用状态的示例,例如:加载,完成或错误。你能提供一个简短的例子吗?

1 个答案:

答案 0 :(得分:1)

不确定这是不是您的意思,但您可以像这样包装异步http调用

const httpStream = Observable.create(observer => {

    fetch('http://server.com')
      .then(response => response.json()) 
      .then(data => {
        observer.next(data); // if http call provides progress as well as completion
                             // these can all be pushed with observer.next()
        observer.complete();
      })
      .catch(err => observer.error(err));

  });

  httpStream.subscribe(data => console.log(data));

当然,如果它实际上是你想要包装你可以改为

var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));

编辑:如果您正在使用角度HttpClient,则无需将其包装,因为它已经是可观察的。要获得进度更新以及最终响应,以下内容应该可以正常工作

const req = new HttpRequest('POST', 'http://api.server.com', body, {
    reportProgress: true
});

this._http.request(req)
.filter((event) => event.type === HttpEventType.UploadProgress || event instanceof HttpResponse)
.map((event) => {
    if (event.type === HttpEventType.UploadProgress) {
        const percentDone = Math.round(100 * event.loaded / event.total);
        return { type: 'uploadProgress', percentDone };
    } else if (event instanceof HttpResponse) {
        return { type: 'httpResponse', status: event.status };
    } 
})
.subscribe((response) => {
    if (response.type === 'uploadProgress') {
        console.log(`upload still in progress - percent done = ${response.percentDone}%`);
    } else {
        console.log(`upload completed  - status = ${response.status}`);
    }
});

事实上,如果您想知道所有请求都已完成,并且不需要每个请求的进度更新,而不是将请求推送到数组中,则更好的选择可能是使用forkJoin - 这类似于promise.all,因为只有在所有子可观察量完成后才能从observable获得输出 - https://www.learnrxjs.io/operators/combination/forkjoin.html