首页 > 解决方案 > 在嵌套结构指令中找不到父服务

问题描述

我正在使用 Angular 8 来构建我的小应用程序。在我的应用程序中,我有 2 个结构指令:

@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);
  }
}
@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,我也想访问DemoServicein 中的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 开始,并且可以通过子结构指令增加。

这是我的预期结果:

预期结果

标签: angularangular2-directivesangular-directive

解决方案


解释:

错误消息表明 Angular 无法注入父指令所需的服务。您应该通过指定提供者详细信息来帮助 Angular 识别所需的服务。有几种方法可以指定。

解决方案:providers: [DemoService]在 app.module.ts 中引入即可解决。


推荐阅读