【发布时间】:2018-10-18 14:39:49
【问题描述】:
我对 RxJS 真的很陌生,我有一个关于 RxJS ajax 请求的问题。我需要将progressSubscriber 实现到 RxJS 的AjaxRequest (因为我需要从 0% 到 100% 显示进度条)。但是,从我编写的代码中,我不确定如何检测请求何时完成,然后我们可以在它发生时采取一些措施。
在检查了我的浏览器console.log() 之后,我想我们可以从progressSubscriber 响应中检测到done 状态是否具有status 属性。因为据我所知,在发出 XHR 请求时,它没有 status 属性。
有没有更好的方法来检测一个请求被认为是done(无论是success还是error)。
目前这是我获得 done 状态的进度(在 ES6 中):
import { Subject } from 'rxjs';
import { ajax as rxAjax } from 'rxjs/ajax';
import { merge } from 'rxjs/operators';
let form_data = new FormData();
form_data.append( 'key', 'value' );
const progressSubscriber = new Subject();
let request$ = rxAjax({
url: 'http://localhost.com/some-api',
method: 'POST',
crossDomain: true,
withCredentials: true,
body: form_data,
progressSubscriber
});
progressSubscriber
.pipe( merge(request$) )
.subscribe( data =>{
if ( data.hasOwnProperty('status') ) {
console.log('XHR is DONE');
}
});
我希望有更优雅的方法来做到这一点。可能有 2 个回调块,例如 promise then(),或 success & error 回调,就像 jQuery Ajax。
提前致谢。
==========更新/进展==============
根据Fan Cheung 的回答,我得到了启发并正在寻找 RxJS 错误和完整签名。看来我过去学过只是忘记了subscribe()的基本知识,它有签名:
-
next()发生时调用的函数 - 发生错误时调用的函数
- 完成/完成时调用的函数
所以,目前的进展我最终得到以下subscribe()(基于上面的代码):
progressSubscriber
.pipe( merge(request$) )
.subscribe(
data =>{
if ( data.type === 'progress' ) {//Detect if it is response of Progress ( not XHR complete response )
let upload_progress = Math.floor(data.loaded / data.total * 100 );
}
if ( data.hasOwnProperty('status') ) {
//This is still the only way i can detect the request get complete
}
},
err => {
console.log( err.target.status ); //Just found that in RxJS, XHR server response is tied into `target` field
},
complete => {
console.log( complete );//Complete will just give "undefined", seem we must really detect from first callback of subscribe() by detect if it has `status field from it response
})
谁有更好的主意,请指教。谢谢。
【问题讨论】:
标签: ajax ecmascript-6 xmlhttprequest rxjs reactivex