我一直试图找到一个将observate包装到订阅服务器中的示例,以监视异步调用的状态,例如加载、完成或出错。你能举个简短的例子吗?

最佳答案

不确定这是否是您的意思,但是您可以这样包装一个异步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,因为您只从observate一旦所有子观测完成-https://www.learnrxjs.io/operators/combination/forkjoin.html

10-06 15:38