Guy*_*y E 4 dependency-injection modal-dialog typescript angular-material angular
我使用一个组件作为通过路由到达的常规组件,但我希望它也将它用作模态对话框的“目标”,当使用注入组件时:
export class Component1 implements OnInit {
constructor(private service: <someService>,
public dialogRef: MatDialogRef<Component1>, //These 2 lines are used as
//injection from the opener
@Inject(MAT_DIALOG_DATA) public data: any) {}
Run Code Online (Sandbox Code Playgroud)
这是“开瓶器”的代码:
openComponent1aSModalPage()
{
Const dialogRef = this.dialog.open(Component1, {
width: '70%',
height: '70%',
data: {property: propertyValue}
});
Run Code Online (Sandbox Code Playgroud)
我在激活开启器时工作,但如果我尝试使用常规路由到达相同的组件,我会得到:
错误:未捕获(承诺):NullInjectorError:StaticInjectorError(AppModule)[Component1 -> MatDialogRef]:StaticInjectorError(Platform:core)[Component1-> MatDialogRef]:NullInjectorError:没有 MatDialogRef 的提供者!
如何调整该组件以在两种模式下工作?
我找到了组件中可选注入参数的解决方案:我在构造函数参数之前添加了 @Optional() 装饰器(只有在注册了提供程序时才应该注入)。
constructor(private service: <someService>,
@Optional() public dialogRef: MatDialogRef<Component1>,
@Optional() @Inject(MAT_DIALOG_DATA) public data: any )
Run Code Online (Sandbox Code Playgroud)
我在这里找到了解决方案: 带有可选参数的 DI 构造函数
| 归档时间: |
|
| 查看次数: |
2517 次 |
| 最近记录: |