angular - 订阅时未更新角度模型字段
问题描述
简化后我得到了一个观点:
<table class="table table-bordered table-striped">
<tr>
<td>
<label>First Name</label>
<input type="text" class="form-control" [(ngModel)]="profile.FirstName">
</td>
<td>
<label>Last Name</label>
<input type="text" class="form-control" [(ngModel)]="profile.LastName">
</td>
</tr>
</table>
构造函数创建空白配置文件并且 ngOnInit 检查更改的组件:
profile: Profile;
sub: any;
constructor(private serv: ProfileService, private route: ActivatedRoute) {
this.profile = new Profile('', '');
}
ngOnInit(): void {
this.sub = this.route.params.subscribe(params => {
const id = params['id'];
this.serv.getProfile(id).subscribe(res => {
console.log(res);
this.profile = res;
// this.profile.LastName = res.LastName; doesn't work either
});
});
}
在控制台上记录了正确的配置文件,但未更新表字段。怎么了?谢谢你的帮助!
解决方案
为了触发其绑定,Angular 正在寻找的是参考更改。
当您像这样分配时,您不会更改参考:
this.profile.LastName = res.LastName;
你想做的是像这样使用传播运算符:
this.profile = { ...this.profile, lastName: res.lastName }
推荐阅读
- quill - QuillJS 预览不是编辑器视图格式问题
- python - 用密钥保存数据为 npz
- sql-server - 有没有办法查明哪一行代码有被零除的错误?
- sql-server - 更改 Visual Studio 数据库项目的发布脚本的编码
- sql-server - 无法将 MS Access 前端连接到 SQL Server 后端
- azure - 如何通过 powershell 脚本或任何其他自动化方式在集成帐户中上传流动文件?
- ssis - SSIS 包将在用 vb 编写的脚本任务中的断点处停止,但在 c# 中不对应
- node.js - 如何使用从 SPA 获得的 azure 广告访问令牌来保护后端 api?
- php - 在当前数组中插入不同的数组值作为键?
- html - 如何阻止视频源的纵横比改变(WebRTC)