angular - .subscribe() 方法中所做的更改未反映在它或模板中
问题描述
我正在使用主题向基本电话簿应用程序添加编辑功能。我在订阅回调内部对组件类变量所做的更改不会反映在它或模板中。
我已经尝试了以下问题的答案中列出的解决方案: Angular 2 View will not update after variable change in subscribe
在 service.ts 中:
startedEditing= new Subject<number>();
在 details.component.ts(数据在 fu 上传递的地方):
onEdit(){
this.contactsService.startedEditing.next(this.id);
}
在 edit-component.ts(在 ngOnInit 中):
this.subscription=this.contactsService.startedEditing.subscribe(
(index:number)=>{
this.editMode=true;
this.editedItemIndex=index;
this.editItem=this.contactsService.getContact(this.editedItemIndex);
this.editForm.setValue({
address:this.editItem.address,
name: this.editItem.name,
phone:this.editItem.phone,
profession:this.editItem.profession
});
console.log("in subscribe: "+this.editedItemIndex);
}
);
console.log("out of it :" + this.editedItemIndex);
}
控制台上的输出:
in subscribe: 0
out of it : undefined
预期结果:
in subscribe: 0
out of it :0
解决方案
his.editedItemIndex
t未定义是正常的console.log("out of it :" + this.editedItemIndex);
。这部分上面的代码是异步的,所以当console.log("out of it :" + this.editedItemIndex);
运行时,订阅里面的代码还没有执行,this.editedItemIndex
也没有初始化。现在,ngOnInit
这是在您的组件中调用的第一个方法,因此在其他方法或模板中,this.editedItemIndex
应该已经初始化并且不是未定义的。可能您可以共享您的 html 代码或其他未定义的地方,以便答案更准确。
推荐阅读
- django - 添加或编辑对象时 Django 管理员崩溃
- ios - 在 UITableView 中从 [(key: String, value: [[String : Any]])] 分配键和值
- amazon-s3 - AWS S3 + Route53:重定向 S3 存储桶没有做任何事情
- angular - 升级后 ng 服务不再可启动
- mysql - 在选择查询中使用!=、“AND”和“OR”时在 MySQL 中没有得到结果..!
- javascript - 如何在 React 应用程序中分隔路由
- reactjs - 在 React 中嵌入 Pinterest 小部件
- wordpress - 我可以根据联系表格 7 中选定的单选按钮来构建电子邮件吗?
- c# - 带有 MsBuild 的 SonarQube:sonar.cs.analyzer.projectOutPaths 不会为此项目加载任何 protobuf 文件
- c# - 从 C# 应用程序自动收集统计信息