在父组件完成渲染后订阅一个可观察的对象-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(,并且传递给子组件的值总是空

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

试着像下面这样添加,

类别组件.ts:

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

相关内容

最新更新