角度:将服务从定制元素传递到子定制元素

问题描述

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

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

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

如果我尝试以这种方式注入 TestService ,则会收到“ NullInjectorError:没有为TestService提供程序!”

但是,如果我在app.module中提供它,那么所有这些都可以再次使用。所以我的问题是,有没有办法解决这个问题,或者这仅仅是CE的解决方法(希望没有)?

解决方法

您应该根据自己的演示解决问题。

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;
  }

}
,

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