如何与 MdDialog 内的组件共享作用域服务?
How to share a scoped service with a component inside an MdDialog?
我的应用有一个 AppComponent 父级和一个 ProductComponent 子级。在 ProductComponent 中,我提供了一项服务,因为我希望该服务仅在 ProductComponent 范围内可用(对于任何未来的孙组件) ).我不想在 NgModule 的根范围内全局提供服务。
@Component({
selector: 'my-product',
providers: [ MyService ],
...
我的 DialogComponent 依赖于服务。但是当我从 ProductComponent...
打开一个对话框时
export class ProductComponent {
openDialog() {
let dialogRef = this.dialog.open(DialogComponent);
}
}
...我得到一个例外:
错误:MyService 没有提供程序
如何将提供的服务从 ProductComponent 转发到 DialogComponent?
请查看我显示问题的最小 Plunker sample。
您还需要在对话框组件中提供该服务。
@Component({
selector: 'my-dialog',
providers: [ MyService ],
template: `<div>Today's lottery number is {{service.lotteryNumber}}.</div>`,
})
export class DialogComponent {
constructor(private service: MyService) { }
}
请看一下修改后的plunker:https://plnkr.co/edit/feYrKfG1CfW785mDERCv?p=preview
在找到 GitHub 上描述的 identical issue 后,我设法解决了这个问题。
您需要将 MdDialogConfig 传递给 dialog.open
函数设置 viewContainerRef,如下所示:
openDialog() {
let config = new MdDialogConfig();
config.viewContainerRef = this.viewContainerRef;
let dialogRef = this.dialog.open(DialogComponent, config);
}
现在 DialogComponent 将从父 ProductComponent 注入依赖服务。我有一个新的 Plunker 显示解决方案。
我的应用有一个 AppComponent 父级和一个 ProductComponent 子级。在 ProductComponent 中,我提供了一项服务,因为我希望该服务仅在 ProductComponent 范围内可用(对于任何未来的孙组件) ).我不想在 NgModule 的根范围内全局提供服务。
@Component({
selector: 'my-product',
providers: [ MyService ],
...
我的 DialogComponent 依赖于服务。但是当我从 ProductComponent...
打开一个对话框时export class ProductComponent {
openDialog() {
let dialogRef = this.dialog.open(DialogComponent);
}
}
...我得到一个例外: 错误:MyService 没有提供程序
如何将提供的服务从 ProductComponent 转发到 DialogComponent?
请查看我显示问题的最小 Plunker sample。
您还需要在对话框组件中提供该服务。
@Component({
selector: 'my-dialog',
providers: [ MyService ],
template: `<div>Today's lottery number is {{service.lotteryNumber}}.</div>`,
})
export class DialogComponent {
constructor(private service: MyService) { }
}
请看一下修改后的plunker:https://plnkr.co/edit/feYrKfG1CfW785mDERCv?p=preview
在找到 GitHub 上描述的 identical issue 后,我设法解决了这个问题。
您需要将 MdDialogConfig 传递给 dialog.open
函数设置 viewContainerRef,如下所示:
openDialog() {
let config = new MdDialogConfig();
config.viewContainerRef = this.viewContainerRef;
let dialogRef = this.dialog.open(DialogComponent, config);
}
现在 DialogComponent 将从父 ProductComponent 注入依赖服务。我有一个新的 Plunker 显示解决方案。