如何使用可观察的rxjs处理空结果 [英] How to handle an empty result with rxjs observable

查看:80
本文介绍了如何使用可观察的rxjs处理空结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可能返回[]结果的API.

HTTP/1.1 200 OK
Date: Tue, 16 Apr 2018 06:06:22 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
Request-Context: appId=cid-v1:...

[]

这是我的代码,在特定情况下不起作用:

getData(): Observable<Thing[]> {
    return this.getData1()
    .pipe(
      flatMap(aData => {
        const ids = aData.map(({ id }) => id);
        const bData = this.getBData(ids); // emty result might be here

        //test subscribe
        this.getBData(ids).subscribe((data) => {
          //just had that for a test, to confirm subsscribe never fires when response is `[]`
          console.log(data);
        });

        return Observable.zip(
          Observable.of(aData),
          bData
        );
      }),
      // map does not executing when api that getting called by `this.getBData(ids)` returns `[]`
      map(([aData, bData]) => {
        // Merge the results
        const data: any = aData.concat(bData).reduce((acc, x) => {
          acc[x.scriptNumber] = Object.assign(acc[x.scriptNumber] || {}, x);
          return acc;
        }, {});
        return Object.values(data);
      })
    );
  }

this.getBData(ids);执行http调用并返回Observable<Thing[]>的类型:

  getBData(ids):Observable<Thing[]> {
    const filters = {
      'id': [ids],
    };
    return this.http.post<Thing[]>('http://localhost:8080/api/thing', JSON.stringify(filters), {
      headers: new HttpHeaders().set('Content-Type', 'application/json')
    });
  }

我在控制台上没有错误.

处理这种情况的最佳实践是什么?

更新:

我确实更改了api,所以现在它以这种方式返回数据:

HTTP/1.1 200 OK
Date: Tue, 17 Apr 2018 09:36:11 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked
Request-Context: appId=cid-v1:...

{
  data: [],
  error: 'OK'
}

通过这种方式,我始终可以对数据进行响应,并且我的代码可以进行一些小的修改(aData.databData.data),但是我仍然想知道为什么在数组为空的情况下它没有出错,因为@DanielWStrimpel认为它应该发出反正还是值...?

解决方案

首先,您的post方法(将空数组视为无响应主体)或API(返回空响应主体而不是空数组)存在问题),无论哪种方式,现在当您获得空数据时,它只会完成请求,什么也不返回.

第二,有一个解决此问题的方法(尽管我更喜欢像您一样将status字段添加到响应正文中),是使用RxJS 解决方案

First, there is a problem with your post method (perceive empty array as no response body) or your API (return empty response body instead of empty array), either ways, now when you get empty data, it will just complete the request and return nothing.

Second, there is a workaround for this problem (while I prefer to add the status field to the response body like you did), is to use RxJS toArray, like this:

this.getBData(ids)
    .pipe(toArray())
    .subscribe(([bData]) => {
      // Process the data
    });

Note: As you can see, toArray emits an array of all items that the Observable emitted, that mean that in your case, if will return either an empty array or an array contains your data array [[item1, item2]].

这篇关于如何使用可观察的rxjs处理空结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆