【发布时间】:2021-12-09 09:17:26
【问题描述】:
我正在学习 Angular 和 Typescript。 现在,我想做这个:
- 从 web api 获取用户列表
public list$:Observable<{id:string,name:string,like:number}[]> = new Observable()
ngOnInit(): void {
this.getData()
}
getData(){
this.list$ = this.service.getUserList()
}
- 呈现用户列表
<ul>
<li *ngFor="let item of list$ | async">
<input (ngModelChange) = "changeName($event,item.id)">
....
</li>
</ul>
- 通过 id 更改用户名
async changeName(newName:string,id:string){
const res = await this.service.changeName(newName,id).toPromise()
if(res.success){
// How to update this.list$ , without send a new request
// just like this:
// this.userList = this.userList.map(i=>i.id === id ? { ...i, name:newName } : i)
}
}
-
这是可以做到的吗?
-
如果是,是应该做的事情,还是有更好的方法来完成我想做的事情?
想!!!!
【问题讨论】:
-
在组件中订阅它,做你的事,渲染它。在 onDestroy() 方法中取消订阅