【发布时间】:2021-12-08 15:35:05
【问题描述】:
我有一个用户数组的主题
private _currentHeroes = new Subject<Hero[]>();
currentHeroes = this._currentHeroes.asObservable();
- 我的目标是只编辑数组的 1 个元素而不订阅
在我的服务中启动用户的功能
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 时达到同样的效果。
我尝试获取主题的值,但由于它是主题,所以不可能。我尝试在线搜索,但不幸的是,我没有找到任何有用的解决方案来满足我的需求。
有人遇到过这个问题吗?或者如何解决?
【问题讨论】:
标签: angular subject subject-observer