在父组件完成渲染后订阅一个 observable - Angular

Subscribe an observable after parent component finish rendering - Angular

我有两个相关组件,在我订阅的父组件中获取产品数据

getProductData(productId) {
    this.magB1BaseService.getProductById(productId)
      .pipe(
        tap(response => {
          if (response.Success && response.Data != null) {
            this.Product = response.Data as Product;
            console.log('Product Data==>', this.Product);
            this.productMedia = this.Product.Media;
            this.prepareMediaFileList();
            this.getAttributeSetAttributes(this.Product.AttributeSet);
          } else {
            this.notification.error('Error', response.Errors[0]);
          }
        })
      )
      .subscribe();
  }

并将产品对象的值传递给子组件

<app-mag-b1-category
              [(recordValue)]="Product.Categories"
              (AddCategory)="addCategory($event)"
              (DeleteCategory)="deleteCategory($event)">
</app-mag-b1-category>

在子组件 (categoryComponent) 中,我正在调用一个函数来处理来自父组件的传入值。

mapRecordValues() {
    if (this.recordValue != null) {
      const selectedCategories = this.recordValue as ProductCategory[];
      selectedCategories.forEach(cat => {
        const category = this.AllCategories.find(x => x.Id === cat.CategoryID);
        const test = this.transformer(category, 1);
        test.selected = true;
        this.selectListSelection.toggle(test);
        this.dataSource._flattenedData.subscribe(data => {
          const obj = data.find(z => z.Id === category.Id);
          if (obj != null) {
            obj.selected = true;
            this.selectListSelection.toggle(obj);
          }
        });
        this.dataSource._expandedData.subscribe(data => {
          const obj = data.find(z => z.Id === category.Id);
          if (obj != null) {
            obj.selected = true;
            this.selectListSelection.toggle(obj);
          }
        });
      });
      this.selectedCategoriesToSend = Object.assign([], this.recordValue);
      this.selectedCategoriesCount = this.selectedCategoriesToSend.length;
    }
  }
}

我的问题是在初始化父组件之前调用函数 (MapRecordValues),并且传递给子组件的值始终为 null

我们需要 ngOnChanges() 生命周期方法才能从父组件获取最新更新的输入值。

尝试像下面这样添加,

category.component.ts :

ngOnChanges(changes: SimpleChanges): void {
    if (changes.recordValue.currentValue && changes.recordValue.currentValue.length) {
         this.mapRecordValues();
    }
}