假设我们有下面这个如下的数据结构:
{
id: 1,
name: 'Parent Object',
children: [
{
id: 2,
name: 'Child 1'
},
{
id: 3,
name: 'Child 2'
}
]
}
我们想要将一个新的子对象添加到这个嵌套对象列表中。
首先,我们需要通过RxJS的map
操作符来获取我们要修改的嵌套对象列表。然后,我们可以使用Angular
的spread
语法来将新的子对象合并到列表中。
代码示例:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data = new BehaviorSubject({
id: 1,
name: 'Parent Object',
children: [
{ id: 2, name: 'Child 1'},
{ id: 3, name: 'Child 2'}
]
});
get data$() {
return this.data.asObservable();
}
addChild(child) {
this.data.next({
...this.data.getValue(),
children: [
...this.data.getValue().children,
child
]
});
}
}
在上面的例子中,我们使用了BehaviorSubject
来创建一个可观察的数据源。然后我们定义了一个addChild
方法,该方法接收一个子对象作为参数,使用spread
语法将新对象合并到原始数据中。最后我们使用next
方法来更新BehaviorSubject
的值。
上一篇:Angular11rxjsswitchmap即使外部可观察对象被触发也不起作用
下一篇:Angular11上出现“No'Access-Control-Allow-Origin'headerispresentontherequestedresource?”的问题。