Angular 处理模型中视图相关属性的最佳方法(从远程服务获取)

Angular 处理模型中视图相关属性的最佳方法(从远程服务获取),angular,Angular,假设我有一个接口,例如: export interface Alert { alertId: string, alertMessage: string, timestamp: Date, alertType: number } 例如,我在组件中显示的 app.component.ts: alerts : Alert[]; ngOnInit(){ this.alerts = this.getAlertsFromRemoteService(); } g

假设我有一个接口,例如:

export interface Alert {
    alertId: string,
    alertMessage: string,
    timestamp: Date,
    alertType: number
}
例如,我在组件中显示的

app.component.ts

alerts : Alert[];

ngOnInit(){
     this.alerts = this.getAlertsFromRemoteService();
}

getAlertsFromRemoteService() : Alert[] {
     //http get request...
}

updateAlertInRemoteService(alert : Alert) {
     //http post request...
}
app.component.html

<tbody>
    <tr *ngFor="let alert in alerts">
         <td>
              <button (click)="updateAlertInRemoteService(alert)">
         </td>
    </tr>
</tbody>

现在,我想在运行
updateAlertInRemoteService
时更改视图(例如,将
tr
的类更改为
disabled
)。这样做的最佳方法是什么

是的,我当然可以将
警报
界面更改为类似于
提交:布尔值
,但这样我就“干扰”了模型的完整性

你会怎么做

谢谢

您可以将“提交”逻辑存储在单独的数组中,该数组在加载数据时进行初始化,并在更新数据时进行切换

警报:警报[];
提交:布尔值[];
恩戈尼尼特(){
this.service.getAlerts().subscribe(警报=>{
this.submitting=alerts.map(()=>false);
this.alerts=警报;
});
}
UpdatelertinRemoteService(索引:编号){
此.submiting[index]=true;
const alert=this.alerts[index];
//http post请求。。。
this.service.update(警报).subscribe(()=>{
此。提交[索引]=false;
});
}
然后HTML可以处理索引并绑定到提交数组


或者,您可以将
updateAlertInRemoteService
的签名保留为当前的签名,并查找已提交的
警报的索引

使用视图模型 这里的另一个选项是使用视图模型

导出接口AlertViewModel{
警惕:警惕;
提交:布尔;
}

您将在组件中创建一个数组,并在视图模型中管理提交状态。这有助于保持原始模型的整洁,并将您的视图问题排除在域模型之外。

您个人是否更喜欢这种方法而不是更改
警报
?这正进入观点领域。我当然希望保持我的域模型的纯净。如果我想在模型中存储一些特定于视图的关注点,我会创建一个视图模型接口