angular - Angular Observable 获取从父组件到子组件的更新更改对象
问题描述
我有一个 Angular 父组件,用于将对象传递给子组件,如下所示
export class ParentComponent implements OnInit {
viewModel = {} as MyViewModel;
constructor(private service: MyService) {}
ngOnInit() {
this.service.subscribe((data) => {
this.viewModel = data.fdForms.viewModel;
});
}
我通过 html 将填充的 viewModel 对象传递给组件
<app-table [viewModel]="viewModel"></app-table>
在我的子组件中,它通过 @Input()
export class TableComponent implements OnInit {
@Input() viewModel = {} as any;
constructor() { }
ngOnInit(): void {
console.log(this.viewModel); // this stays null even when parent is updated
}
}
经过测试,父组件在发生变化时得到了更新的数据,而子组件没有传递更新的对象。
谷歌搜索后,我想我需要更改代码以使子组件订阅父 viewModel 对象属性。
更新:尝试 OnChanges 但出现错误
export class TableComponent implements OnChanges {
@Input() viewModel = {} as any;
constructor() { }
ngOnChanges(changes: SimpleChange) : void {
console.log(this.viewModel); // this stays null even when parent is updated
}
}
但我收到了这个错误。我检查了 OnChanges 上的其他帖子,不知道是什么错误
Error TS2416: Property 'ngOnChanges' in type 'TableComponent' is not assignable to the same property in base type 'OnChanges'.
Type '(changes: SimpleChange) => void' is not assignable to type '(changes: SimpleChanges) => void'.
Types of parameters 'changes' and 'changes' are incompatible.
Type 'SimpleChanges' is missing the following properties from type 'SimpleChange': previousValue, currentValue, firstChange, isFirstChange
28 ngOnChanges(changes: SimpleChange) {
感谢新手的任何帮助。
解决方案
ngOnInit
创建组件时执行。因此,在这种情况下,很可能是在创建子组件时service
,父组件尚未通知任何值,因此控制台上没有打印任何内容。
所以你有一些不同的策略来克服这个问题。
一种是service
通过依赖注入传递给 Child,然后在 Child 组件中传递subscribe
给它。ngOnInit
但也许你应该看看你viewModel
在 Child 中的使用方式。如果您在模板中引用它,您应该能够在更改发生时看到它们。
检查新值是否实际传递的另一个技巧,您可以viewModel
像这样对属性使用 getter/setter。
_viewModel: any;
get viewModel() {
return this._viewModel;
}
@Input() set viewModel(value: any) {
this._viewModel = value;
console.log(this._viewModel); // this should print something when new data is received
}
推荐阅读
- java - 如何根据搜索框向JTable插入数据?
- node.js - 在 AWS Amplify 上为 Express 和 React 设置代理
- angular - 有没有办法在编译时管理角度路线?
- html - 如何消除与“writing-mode: vertical-rl;”相关的空白?
- r - R中的grepl在子集时无法正常工作
- keras - 保护边缘板上的 keras 模型
- python - 根据键列表过滤字典
- networking - 如何应用 kubernetes 网络策略来限制从其他命名空间访问命名空间?
- .net - 为什么在 vb.net 中调整窗体顶部或左侧的大小时,无边框窗体会闪烁?
- javascript - 如何动态加载 mailchimp 脚本