【问题标题】:RxJS AJAX detect request is done from progressSubscriber ( whether success or error )RxJS AJAX 检测请求是从 progressSubscriber 完成的(无论是成功还是错误)
【发布时间】: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


    【解决方案1】:

    使用isLoading 属性进行跟踪,点击运算符到switch isLoading 状态

    merge(progressSubscriber.pipe(tap(()=>
    this.upload_progress = Math.floor(data.loaded / data.total * 100 )
    ),
    request$.pipe(tap(res)=>{},catchError((e)=>{..})
    ).subscribe()

    【讨论】:

    • 谢谢你的回答,不过我也喜欢听progressSubscriber。所以,我可以有一个进度条以及 XHR 上传进度。我如何使用您的解决方案来收听它?
    • 其实这不仅仅是一个简单的isLoading true,而是我真的需要一个从0%到100%的进度条。所以我一定要用progressSubscriber
    • 在这种情况下,您可以像更新的答案一样构建您的代码,那么就不需要 if ...
    猜你喜欢
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多