我有 2 个主要组件,我想将数据从这些组件传递到子组件。
FirstMainComponent 正在将数据传递给 ChildComponent
@Component({
...
providers: [DialogService]
})
export class FirstMainComponent implements OnInit {
constructor(public dialogService: DialogService){}
...
const dialogRef= this.dialogService.open(ChildComponent, {
header: 'Something',
width: '90%',
baseZIndex: 100000,
closeOnEscape : true,
closable : true,
data: {
Code: '1001',
Name:'Something'
}
});
dialogRef.onClose.subscribe((async (childModel: ChildModel) => {
// my code
}));
}
SecondMainComponent 未将数据传递给 ChildComponent
@Component({
...
providers: [DialogService]
})
export class SecondMainComponent implements OnInit{
constructor(){
public dialogService: DialogService
}
...
const dialogRef= this.dialogService.open(ChildComponent, {
header: 'Something',
width: '90%',
baseZIndex: 100000,
autoZIndex: true,
closeOnEscape: true,
data: {
Code: '1002'
}
});
dialogRefFindCustomers.onClose.subscribe((childModel: ChildModel) => {
// my code
}
}
});
}
这是子组件
@Component({
...
// no providers
})
export class ChildComponent implements OnInit {
constructor(){
public ref: DynamicDialogRef,
public config: DynamicDialogConfig
}
...
console.log("this.config.data");
console.log(this.config.data);
this.ref.close();
}
将数据从 SecondMainComponent 传递到 ChildComponent 时遇到此错误
NullInjectorError:StaticInjectorError(AppModule)[CustomerSearchComponent -> DynamicDialogRef]:
类型错误:无法读取未定义的属性(读取“实例”)
如果我按如下方式更改 ChildComponent 提供程序字段,FirstMainComponent 和 SecondMainComponent 会出现错误。
providers: [DynamicDialogRef, DynamicDialogConfig]
未捕获(承诺中):类型错误:无法读取未定义的属性(读取“代码”)
因为
this.config.data
=未定义
我建议您使用单独的服务,在打开对话框之前设置属性。
这样做,您可以轻松访问您孩子的数据。