【发布时间】:2021-01-15 18:26:20
【问题描述】:
我正在研究英雄的角度之旅示例。有一项功能可以将新英雄添加到现有英雄列表中。 我在 hero.service.ts 中添加英雄的方法如下:
addNewHero(hero : Hero) : Observable<Hero> {
console.log(hero)
return this._http.post<Hero>(this.url,hero).pipe(
tap(res => this._service.addMessage(`new hero is ${hero.name} added`)),
catchError(error => this.handleerror('adding a hero'))
)
}
Heroescomponent 类中的 addHero 方法如下:
export class HeroesComponent implements OnInit {
heroes : Observable<Array<Hero>>;
selectedHero: Hero;
constructor(private _service : HeroService,private _router : Router) { }
ngOnInit() {
this.heroes = this._service.getHeroes()
}
onSelect(hero: Hero): void {
this.selectedHero = hero;
}
details(id : Number) {
this._router.navigate(['heroes',id])
}
**addHero(name : String){
console.log(name)
this._service.addNewHero({ name } as Hero).subscribe((res : Hero) => {
this.heroes = this._service.getHeroes()
})
}**
}
Heroes.HTML 文件如下:
<h2>My Heroes</h2>
<div>
<input type="text" #heroname>
<button (click) = "addHero(heroname.value)">Add</button>
</div>
<ul class="heroes">
<li *ngFor="let hero of heroes | async">
<a routerLink = "/detail/{{hero.id}}"
style = "text-decoration : none"><span class="badge">{{hero.id}}</span> {{hero.name}}</a>
</li>
</ul>
我正在使用heroes 类型为Observable<Hero[]> 的变量。
所以,每当我添加一个新英雄时,我都想在现有的heroes 中添加一个新添加的英雄。但是,我无法做到这一点,因为observable of arrays 没有推送方法。所以,我再次调用getHeroes 方法来刷新列表以显示新添加的项目。是否有任何解决方法将项目添加到数据类型Observable<Array> 而不是再次访问服务器
【问题讨论】:
标签: arrays angular rxjs-observables