代码之家  ›  专栏  ›  技术社区  ›  Jeanluca Scaljeri

Angular:将服务从自定义元素传递给子自定义元素

  •  0
  • Jeanluca Scaljeri  · 技术社区  · 4 年前

    我建了一个 demo 它创建了2个自定义角度元素(结账应用程序模块)。工作起来很有魅力,但有一个问题,如果我在父元素(称为BarComponent)中提供服务,它的子CE(称为TestComponent)不会接收到它

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

    在其html内部,它呈现子CE: TEST-CE: <test-ce></test-ce>

    如果我尝试注射 测试服务 这样我就得到了“NullInjectorError:没有TestService的提供者!”

    但如果我在app.module中提供它,一切都会再次正常工作。所以我的问题是,有没有办法解决这个问题,或者这只是特首的做法(希望没有)?

    2 回复  |  直到 4 年前
        1
  •  1
  •   JackyShows    4 年前

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

    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
  •  0
  •   user14438281    4 年前

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