如何在 Angular 中管道/映射 Observable [英] How to pipe / map an Observable in Angular

查看:14
本文介绍了如何在 Angular 中管道/映射 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个嵌套对象显示为 [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屋!

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