我正在尝试注入ViewContainerRef服务,但收到错误No provider for ViewContainerRef!。我找到了这个PR,它准确地解决了我所追求的问题,并且它似乎已被合并。
请注意,我知道如何通过使用 this 的占位符来实现这一点。
服务对于任何视图来说都是完全不可知的。如果您尝试将服务与特定视图关联,那么您应该将其添加到特定父组件/指令内的提供程序列表中,并将 ViewContainerRef 作为参数传递到服务的方法之一。
通过将 viewContainerRef 添加为 app.module(并且仅是 app 模块)中的提供者,使您在单例中需要 viewContainerRef 的服务;将该服务注入到需要其构造函数的 containerRef 的组件中,并让它调用服务中的 setter 方法,将其 containerRef 设置为服务中的变量以供将来使用。
您想要传递其引用的组件
export class PrintPortalComponent {
constructor(
private printPortalService: PrintPortalService,
public viewContainerRef: ViewContainerRef
) {
this.printPortalService.printPortalRef = this.viewContainerRef;
}
}
Run Code Online (Sandbox Code Playgroud)
您的单身服务
export class PrintPortalService {
public viewContainerRef: ViewContainerRef;
set printPortalRef(vcr: ViewContainerRef) {
this.viewContainerRef = vcr;
}
}
Run Code Online (Sandbox Code Playgroud)
我为此苦苦挣扎了几个小时,直到我发现:How do I create a singleton service in Angular 2?
| 归档时间: |
|
| 查看次数: |
6057 次 |
| 最近记录: |