首页 > 解决方案 > 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) {

感谢新手的任何帮助。

标签: angularrxjs

解决方案


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
}

推荐阅读