更改管道中对象的属性 (rxjs)

ahm*_*dkh 2 javascript observable rxjs typescript angular

我有一个对象Person

interface Person {
  name: string;
  age: number;
}
Run Code Online (Sandbox Code Playgroud)

我得到了一个Persons使用 observable的流。

getPersons(): Observable<Person> {
  return this.myService.getPerons.subscribe(data);
}
Run Code Online (Sandbox Code Playgroud)

我想对年龄字段进行修改并保持名称不变

person.age = person.age + 2;
Run Code Online (Sandbox Code Playgroud)

例子:

原始流:{name:'John doe',年龄:40}。

应用管道后:{name. 'John doe',年龄:42}

我想这.subscribe(data).pipe(map(e => ...))不是这里的解决方案,我正在寻找适用于管道的替代方案

Mic*_*l D 7

You could do it with map operator in the service. Try the following

myService

getPerons(): Observable<Person> {
  this.http.get('url').pipe(map(response => ({...response, age: response.age + 2})));
}
Run Code Online (Sandbox Code Playgroud)

And you could subscribe as usual in the component

this.myService.getPerons.subscribe(data => { this.persons = data });
Run Code Online (Sandbox Code Playgroud)

  • 您只返回数字,而不返回对象映射(data =&gt;({...data,age:data.age + 2})) (3认同)