【发布时间】:2021-11-29 11:45:23
【问题描述】:
我正在编写一个管理员可以升级用户权限的应用程序。
在我向服务器发送请求以增加用户的权力之后。我从服务器返回用户列表:
powerUp(id: number) {
return this.http
.post<Hero[]>(environment.apiUrl + 'heroes/powerUp/' + id, {})
.pipe(
map((heroes) => {
this.currentHeroes.next(hero);
})
);
}
这里是主题:
private currentHeroes = new BehaviorSubject<Hero[]>(null);
currentHeroes$ = this.currentHeroes.asObservable();
问题是它不是官方的,因为我只能从服务器返回正在启动的特定用户。
powerUp(id: number) {
return this.http
.post<Hero[]>(environment.apiUrl + 'heroes/powerUp/' + id, {})
.pipe(
map((hero) => {
// update the particular hero in the currentHeroes subject
})
);
}
我的问题是如何在没有.next() 的情况下修改 currentHeroes 主题(仅限更新的用户)而不从服务器返回整个列表。
我已尝试关注:
powerUp(id: number) {
return this.http
.post<Hero>(environment.apiUrl + 'heroes/powerUp/' + id, {})
.pipe(
map((updatedHero) => {
this.currentHeroes$.pipe(
// doesn't enter here
map((oldHeroes) => {
const index = oldHeroes.findIndex((hero) => hero.id === id);
oldHeroes[index] = updatedHero;
})
);
})
);
}
英雄卡模板
export class HeroCardComponent implements OnInit {
@Input() hero: Hero;
constructor(public heroService: HeroService, private toastr: ToastrService) {}
ngOnInit(): void {}
powerUp(id: number, name: string) {
this.heroService.powerUp(id).subscribe(() => {
this.toastr.success(`${name} was successfully powered up!`);
});
}
delete(id: number, name: string) {
this.heroService.delete(id).subscribe(() => {
this.toastr.success(`${name} was successfully deleted`);
});
}
}
谁能解释一下我该怎么做?
【问题讨论】: