【问题标题】:Transform API response in Angular rxjs在 Angular rxjs 中转换 API 响应
【发布时间】:2021-03-25 07:54:51
【问题描述】:

您好,我收到了来自 API 的回复:

{
   "records":[
      {
         "id":1,
         "motivazione":"",
         "autorizzazione":false,

      }
   ]
}

我该如何转换它:

[
      {
         "id":1,
         "motivazione":"",
         "autorizzazione":false,

      },
   ]

谢谢

约瑟夫

【问题讨论】:

  • 这和 Angular 或 RXjs 有什么关系?此外,您正在开发一个带有 Observables 的 Angular 应用程序,但您不知道如何从数组或对象中提取元素?友好的建议,也许你应该在处理 Angular 之前学习一些“Javascript 101”教程 :)

标签: javascript angular api rxjs


【解决方案1】:

问题不清楚。如果您只需要获取属性records 的内容,您可以通过管道将pluck 运算符传递给HTTP 请求。

import { pluck } from 'rxjs/operators';

public someFunction(): Observable<any> {
  return this.http.get(url).pipe(
    pluck('records')
  );
}

您也可以使用map 运算符。

import { map } from 'rxjs/operators';

public someFunction(): Observable<any> {
  return this.http.get(url).pipe(
    map((res: any) => res['records'])
  );
}

【讨论】:

    【解决方案2】:
    You can use the map operator in rxjs to transform your data. More precisely if you only want the records property from your response object you can do that as following: 
    
    import { map } from 'rxjs/operators';
    
    transformData(){
         this.http.get(url).pipe(map((target: any) => target.records)).subscribe((data) => {
       console.log(data);
        })}
    

    这将只返回响应对象的记录属性。

    【讨论】:

    • 您不能从订阅的回调中返回值。
    • @MichaelD 是的!修好了。
    猜你喜欢
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2019-11-20
    • 2021-09-14
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多