angular - 在嵌套结构指令中找不到父服务
问题描述
我正在使用 Angular 8 来构建我的小应用程序。在我的应用程序中,我有 2 个结构指令:
parent.directive.ts
:
@Directive({
selector: '[parent]',
providers: [
DemoService
]
})
export class ParentDirective implements OnInit {
public constructor(protected viewContainerRef: ViewContainerRef,
protected templateRef: TemplateRef<any>,
public demoService: DemoService) {
}
public ngOnInit() {
this.demoService
.name = 'parent';
this.viewContainerRef.createEmbeddedView(this.templateRef);
}
}
- child.directive.ts:
@Directive({
selector: '[child]',
providers: [
DemoService
]
})
export class ChildDirective implements OnInit {
public constructor(protected viewContainerRef: ViewContainerRef,
protected templateRef: TemplateRef<any>,
public demoService: DemoService,
@SkipSelf() public parentDemoService: DemoService) {
}
public ngOnInit() {
this.demoService
.name = 'parent';
console.log(this.parentDemoService.name);
}
}
我的 2 个指令都初始化 a DemoService
,但是,在 中child.directive.ts
,我也想访问DemoService
in 中的parent.directive.ts
。
因此,在 中child.directive.ts
,我将 DI 声明如下:
public constructor(protected viewContainerRef: ViewContainerRef,
protected templateRef: TemplateRef<any>,
public demoService: DemoService,
@SkipSelf() public parentDemoService: DemoService) {
}
这是我在html页面中使用的:
<div *parent>
<div>Inside parent</div>
<div *child>
<div>Inside child</div>
</div>
<div *parent>
<div>Inside parent parent</div>
<div *child>
<div>Inside child</div>
</div>
</div>
</div>
</div>
</div>
我希望我可以DemoService
通过实例访问父指令中的parentDemoService
,但我收到以下错误:
ERROR 错误:StaticInjectorError(AppModule)[ParentDirective -> DemoService]: StaticInjectorError(Platform: core)[ParentDirective -> DemoService]: NullInjectorError: No provider for DemoService!
我已经将我的演示代码放在了stackblitz上。
谁能帮我解决这个问题?谢谢你。
P/s:我想为每个指令提供新的实例。这就是我在父子指令中使用提供者的原因
因为有些人不理解我的问题(也许我认为还不够清楚),所以我更新了 2 张图片来描述我的问题。
比方说,DemoService
有一个计数器变量,在父级中从 1 开始,并且可以通过子结构指令增加。
这是我的预期结果:
解决方案
解释:
错误消息表明 Angular 无法注入父指令所需的服务。您应该通过指定提供者详细信息来帮助 Angular 识别所需的服务。有几种方法可以指定。
解决方案:providers: [DemoService]
在 app.module.ts 中引入即可解决。
推荐阅读
- reactjs - 为什么是的字符串验证在它是一个对象时不会抛出错误?
- tensorflow - 如何在 Tensorflow 对象检测 API 中查找边界框坐标
- sql-server - 在外部数据源“(null)”中指定了错误或不可访问的位置
- reactjs - 按钮 onClick 事件未更新组件状态
- vhdl - 使用 vhdl-2008 分析、详细说明、运行和转储 vcd 文件的 GHDL 脚本?
- javascript - 无法读取 mdbreact 中未定义的属性“0”
- javascript - 如何使用 qunit 在 TypeScript 中将函数参数声明为“QUnit”类型?
- android - 在调试设备上测试时显示 UPDATE_NOT_AVAILABLE 的应用内更新 API
- nix - 向 Nix 询问有关给定包的元数据
- scala - Scala mockito:延迟 Mockito.when().thenReturn(someFuture)