【发布时间】:2020-09-04 03:34:49
【问题描述】:
我正在开发一个角度应用程序,我可以说我是角度方面的新手。在我的应用程序中,我通过带有可观察数组的 httpclient 将来自服务器的数据绑定到如下所示的基本列表。我添加了一个新项目以在不同的组件中列出。列表组件和添加新项目组件都在同一页面上。
我对绑定数据和添加新数据没有任何问题。添加新项目后出现问题。在我将新项目添加到列表的数据源后,整个组件都会刷新;但我不想要这个,我想添加新元素而不刷新列表。
简化代码在这里。 我的包含列表的组件:
export class GroupSetupComponent implements OnInit {
dataSet$: Observable<Group[]>;
constructor (private groupService : GroupService) {}
ngOnInit(): void {
this.getGroups();
}
getGroups() {
this.dataSet$ = this.groupService.getGroups();
}
refreshGroupList(group: Group) {
if(group) {
// I have tried getting all list from database again
// this.getGroups();
// than I tried to add new item to existing observable array
this.dataSet$ = this.dataSet$.
pipe(
map(data =>
{
data.push(group);
return dataSet;
}));
}
}
}
及组件模板:
<div *ngIf="dataSet$ | async as resultSet;">
<mat-card>
<mat-card-content>
<mat-selection-list>
<mat-list-option *ngFor="let item of resultSet;" [value]="item.id" [disableRipple]="true">
{{item.name}}
</mat-list-option>
</mat-selection-list>
</mat-card-content>
</mat-card></div>
refreshGroupList 函数是在将新项目添加到数据库并从 api 获取成功消息后从子组件触发的。
我想问,我的做法对不对?如果不是,那么在列表上执行这种 crud 操作的有效方法是什么?
【问题讨论】:
-
也许你想使用trackBy?见这篇文章:medium.com/better-programming/…
标签: angular typescript rxjs angular-material