Angular–编辑/删除主题数组中的元素



我有一个主题的用户数组

private _currentHeroes = new Subject<Hero[]>();
currentHeroes = this._currentHeroes.asObservable();
  • 我的目标是在不订阅的情况下只编辑数组的一个元素

在我的服务中为用户通电的功能

powerUp(id: number) {
return this.http
.post<Hero>(environment.apiUrl + 'heroes/powerUp/' + id, {})
.pipe(
tap((updatedHero: Hero) => {
this._currentHeroes.next(
// I would like to edit the specific element in the array and than sort them by the power.
);
})
);
}

删除我的服务中的用户的功能

delete(id: number) {
return this.http.delete<Hero>(environment.apiUrl + 'heroes/' + id).pipe(
tap((deletedHero) => {
this._currentHeroes.next(
// Here I delete the specific element from the array
);
})
);
}

如果主题是BehaviorSubject,那么我会这样做:

powerUp(id: number) {
return this.http
.post<Hero>(environment.apiUrl + 'heroes/powerUp/' + id, {})
.pipe(
tap((updatedHero: Hero) => {
this._currentHeroes.next(
this._currentHeroes.value
.map((hero: Hero) =>
hero.id === updatedHero.id ? updatedHero : hero
)
.sort((a, b) => a.currentPower - b.currentPower)
);
})
);
}
delete(id: number) {
return this.http.delete<Hero>(environment.apiUrl + 'heroes/' + id).pipe(
tap((deletedHero) => {
this._currentHeroes.next(
this._currentHeroes.value.filter(
(hero: Hero) => hero.id !== deletedHero.id
)
);
})
);
}

但我的目标是在使用Subject而不是BehaviorSubject时实现同样的目的。

我试着了解这个主题的价值,但这是不可能的,因为它是一个主题。我试着在网上搜索,但不幸的是,我没有找到任何有用的解决方案来满足我的需求。

有人遇到这个问题吗?或者如何修复?

我假设您正在处理一个服务,那么您可以在服务属性中有一个需要修改的数组的引用。

heroes = [];

然后,在每次操作之后,您可以修改这些值,然后使用Subject或Behavior Subject或您想要使用的任何东西进行发射。

powerUp(id: number) {
return this.http
.post<Hero>(environment.apiUrl + 'heroes/powerUp/' + id, {})
.pipe(
tap((updatedHero: Hero) => {
//modify data reference, to add, update or delete value
// in this case modify with powerup
this.heroes = this.heroes
.map((hero: Hero) =>
hero.id === updatedHero.id ? updatedHero : hero
)
.sort((a, b) => a.currentPower - b.currentPower)
// emit the resuelt after every operation 
this._currentHeroes.next(
this.herores
);
})
);
}

记住,您必须订阅每一个返回可观察结果的操作,就像您在代码中显示的那样。

// for example to hero with id 2
this.yourHeroService.powerUp(2).subscribe()

最新更新