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

查看:53
本文介绍了如何在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天全站免登陆