用.map转换Observable [英] Transforming Observable with .map

查看:119
本文介绍了用.map转换Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在转换可观察对象时遇到问题.详细信息如下:

I have a problem with transforming my observable. Details below:

我有这样的数据

[
    {
      'firstName': 'John',
      'lastName': 'Cash',
      'age': 20
    }
  ];

然后我从api中获得了这些数据:

Then I get this data from api:

  public getData(): Observable<Data[]> {
    return this.http.get('xxx')
    .map(
      response => response.json()
    );
  }

然后,我正在尝试订阅此内容:

Then, I'm trying to subscribe this:

this.service.getData.subscribe(
        (res) => this.data = res
      );

没关系,它正在工作.但是我需要修改对象的结构,并且我想使用.map将接收到的对象转换为该模式:

And It's ok, it's working. But I need to modify the structure of object and I would like to use .map to transform received object to this schema:

[
    {
      'firstName': 'John',
      'lastName': 'Cash',
      'age': 20,
'newProperty': 'value'
    }
  ];

..对我没有任何帮助..:/即使我不想添加新属性,但要修改例如firstName的值,

.. and nothing working for me.. :/ Even if I don't want to add new property, but modify a value on for example firstName:

  .map(
    return x => x[0].firstName = 'asd'
  )

它不起作用(类型'string'不能分配给类型'Data []',我知道它的意思,但是我不知道该怎么做,我的错误在哪里?)

it's not working (Type 'string' is not assignable to type 'Data[]', I know what it means, but I don't know how to do that, where is my mistake?)

推荐答案

Observable中的 map 运算符与数组的 map 方法有所区别.您想要将HTTP请求的结果转换为数组,然后对该数组的每个成员应用一些其他转换.让我们一步一步来.

There's a difference between map operator in Observable and map method of array. You want to transform the result of HTTP request to array and then apply some additional transformation to every member of that array. Let's go step by step.

this.http.get('...')

这将返回Observable对象,该对象包含angular的Http服务的Response.要利用其中的数据,您必须调用Response的 json()方法.

This returns the Observable object, which holds the Response of angular's Http service. To make use of the data inside of it, you have to call Response's json() method.

.pipe(
  map((response:Response) => response.json())
)

此代码的意思是当可观察对象发送一些数据时,将其放入处理管道中.将其视为HTTP响应,并将其内容提取为JSON,然后放入另一个可观察的对象".因此,如果您订阅它,您将获得阵列.

This code means 'when the observable sends some data, put it into a processing pipe. Treat it as HTTP response and extract its content as JSON, then put to another Observable'. So if you subscribe to it, you'll get your array.

然后,您可以使用该常规数组执行任何操作,例如使用其 map 方法.让我使用我自己的示例,尽管它与您的示例非常相似.

Then you can do anything with that regular array, like using its map method. Let me use my own example though it's very similar to yours.

this.http.get('...')
.pipe(map((response:Response) => response.json()))
.subscribe((array:Person[]) => {
     let modifiedArray = array.map((item:any) => {
           item.newProperty = 'value';
     }

     this.persons = modifiedArray;
});

或者,如果您愿意,可以在订阅之前处理数组项:

Or, if you like to, manipulate array items before subscription:

const modifiedData$:Observable<Person> = this.http.get('...').pipe(
  map((response:Response) => response.json()),
  map((array:Person[]) => {
     return array.map((item:Person) => {
           item.newProperty = 'value';
     }
)};

管道中的

两个连续的 map 运算符可以替换为一个:

Two consecutive map operators in pipe can be replaced with a single one:

const modifiedData$:Observable<Person[]> = this.http.get('...')
  .pipe(map((response:Response) => {
     return response.json().map((item:Person) => {
       item.newProperty = 'value';
     }
  });

modifiedData$.subscribe((persons:Person[]) => {
     this.persons = modifiedArray;
});

如果对您来说太罗here了,这是一个更紧凑(但可读性更差)的版本:

If it's too wordy to you, here's a more compact (but less readable) version:

this.http.get('...')
.pipe(map(response => response.json().map(item => item.newProperty = 'value')))
.subscribe(persons => this.persons = persons);

这篇关于用.map转换Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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