如何解决角度:将服务从定制元素传递到子定制元素
我已经构建了一个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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。