【问题标题】:How to format the API response through a callback function in angular如何通过 Angular 中的回调函数格式化 API 响应
【发布时间】:2020-01-28 22:36:57
【问题描述】:

我想通过回调函数格式化我的 API 响应并获取角度订阅中的数据

我用过mergemap但是没用

this.http.get('https://some.com/questions.xml', {headers, responseType: 'text'})
  .mergeMap(
    res => xml2js.parseString(
      res,
      { explicitArray: false },
      (error, result) => {
        if (error) {
          throw new Error(error);
        } else {
          console.log(result);
          return result;
        }
      }
    )
  ).subscribe(
    data => { console.log("response", data); },
    error => { console.log(error); }
  );

我想在订阅中获取响应 JSON,但我得到了 TypeError:您在预期流的位置提供了无效对象。您可以提供 Observable、Promise、Array 或 Iterable。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    就像 xdeepakv 提到的,当使用 mergeMap or switchMap ...etc 时,你应该返回一个 promise 或 observable。而xml2js.parseString(...) 的类型为SAXParser。因此,您应该使用map

    或者您可以查看this stackoverflow 问题,了解如何将parseString(...) 转换为promise。

    【讨论】:

      【解决方案2】:

      MergeMap 期望作为数据流。您正在返回值并抛出错误。你必须从那里返回一个承诺。

      // RxJS v6+
      import { fromEvent } from 'rxjs';
      import { ajax } from 'rxjs/ajax';
      import { mergeMap } from 'rxjs/operators';
      
      // free api url
      const API_URL = 'https://jsonplaceholder.typicode.com/todos/1';
      
      // streams
      const click$ = fromEvent(document, 'click');
      
      click$
        .pipe(
          /*
           * Using mergeMap for example, but generally for GET requests
           * you will prefer switchMap.
           * Also, if you do not need the parameter like
           * below you could use mergeMapTo instead.
           * ex. mergeMapTo(ajax.getJSON(API_URL))
           */
          mergeMap(() => ajax.getJSON(API_URL))
        )
        // { userId: 1, id: 1, ...}
        .subscribe(console.log);
      

      更多信息。请查看 RXJS 文档。 https://www.learnrxjs.io/operators/transformation/mergemap.html

      【讨论】:

      • 感谢 xdeepakv。兑现了承诺,它奏效了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 2021-10-26
      • 2018-06-25
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多