如何在 Angular 中管道/映射 Observable

编程入门 行业动态 更新时间:2024-10-19 06:22:36
本文介绍了如何在 Angular 中管道/映射 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

一个嵌套对象显示为 [object Object],所以我试图通过管道和地图投射它,但我没有得到任何地方.我已经尝试将模型作为类和接口,但没有帮助.有人能告诉我我做错了什么吗?谢谢.

A nested object is showing up as [object Object] so I'm trying to cast it via pipe and map but I'm not getting any where. I've tried the models as classes and interfaces but no help. Can someone tell me what I'm doing wrong? Thanks.

功能:

  getClients(customerId: number): Observable<Client[]> {
    let clientUrl = 'SOME_URL';
    return this.http.get<Client[]>(clientUrl)
      .pipe(map(client: Client) => client.address as Address);
  }

模型:

import { Address } from './address.model';

export class Client{
  id: number;
  name: string;
  accountNumber: string;
  addressId: number;
  phoneNumber: string;
  address: Address;
}


export class Address{
  id: number;
  name: string;
  addressLine1: string;
  addressLine2: string;
  city: string;
  postalCode: string;
}

我收到错误:错误 TS2345 (TS)地址"类型的参数不能分配给OperatorFunction<{}, Client[]>"类型的参数.

I'm getting the error: Error TS2345 (TS) Argument of type 'Address' is not assignable to parameter of type 'OperatorFunction<{}, Client[]>'.

推荐答案

1) 从 getClients() 方法中移除管道部分

1) remove the piping part from your getClients() method

2) 在订阅 getClients() 之前执行管道映射或创建另一个方法,该方法只会执行管道部分,并从 getClients() 返回的可观察对象

2) do the pipe-map before subscribing to getClients() or create another method, that will do only the piping part with the observable returned from getClients()

mapToAddress(): Observable<Address[]> {
  this.getClients.pipe(
    map((clients: Client[]) => clients.map(client => client.address))
  )
}

理解这一点很重要:当你在 .pipe() 中调用 .map() 方法时,在这种情况下你不会得到一个客户端,你会得到整个客户端数组,推送到 Observable.因为您映射了存储在 Observable 中的值 - 类型的值:<客户端[] >.

This is important to understand: when you call .map() method inside .pipe(), you're not getting a single client in this case, you get the whole clients array, pushed to Observable. Because you map the values, that are stored in the Observable - the values of type: < Client[] >.

你的管道映射可以在一些 Observable 上工作,它发出一个

类型的客户端.客户端 >,不是数组.

Your pipe-map would work on some Observable, that emits a single client of type < Client >, not an array.

这篇关于如何在 Angular 中管道/映射 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 16:14:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:管道   如何在   Angular   Observable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!