【问题标题】:Angular: pass service from custom element to child custom elementAngular:将服务从自定义元素传递给子自定义元素
【发布时间】:2020-10-12 20:22:33
【问题描述】:

我已经构建了一个demo,它创建了 2 个自定义角度元素(结帐 app.module)。像魅力一样工作,但有一个问题,如果我在父元素(称为 BarComponent)中提供服务,它的子 CE(称为 TestComponent)不会收到它

@Component({
  templateUrl: './bar-ce.component.html',
  providers: [TestService] // <-- this one!!
})
export class BarComponent {}

在其 html 中呈现子 CE:TEST-CE: &lt;test-ce&gt;&lt;/test-ce&gt;

如果我尝试以这种方式注入我的 TestService,我会得到“NullInjectorError: No provider for TestService!”

但如果我在 app.module 中提供它,一切都会再次运行。所以我的问题是,有没有办法解决这个问题,或者这只是 CE 的方式(希望不是)?

【问题讨论】:

    标签: angular dependency-injection custom-element angular-dependency-injection


    【解决方案1】:

    你应该根据你的演示解决你的问题。

    TEST-CE: <test-ce [testService]="testService"></test-ce>
    

    然后在你的子组件上这样做。

    import { Component, Input, OnInit } from '@angular/core';
    
    import { TestService } from '../test.service';
    
    @Component({
      templateUrl: './test.component.html',
      styleUrls: ['./test.component.css']
    })
    export class TestComponent implements OnInit {
    
      @Input() testService: TestService
    
      numInput: number;
    
      constructor() { 
        console.log('test-ce constructor.');
      }
    
      ngOnInit() {
        this.numInput = this.testService.value;
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      应该在模块中提供共享服务。并在构造函数中初始化latar(私有testService:Testservice)

      【讨论】:

      • 你确定吗?因为如果显然不使用 CE,这是一种非常合法的服务共享方式
      猜你喜欢
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      相关资源
      最近更新 更多