Angular 传递从注入到父级的服务接收的值';子组件的构造函数
向子级和父级注入服务的方式是什么?最初的想法是将类字段设置并共享给所有子组件。我得到错误Angular 传递从注入到父级的服务接收的值';子组件的构造函数,angular,Angular,向子级和父级注入服务的方式是什么?最初的想法是将类字段设置并共享给所有子组件。我得到错误预期为1个参数,但在子组件上得到0。我找到了,但它破坏了组件的行为 @Component({}) export class ParentComponent{ protected value: any; constructor(someService: SomeService){ this.value = someService.someValue; } } @Component
预期为1个参数,但在子组件上得到0
。我找到了,但它破坏了组件的行为
@Component({})
export class ParentComponent{
protected value: any;
constructor(someService: SomeService){
this.value = someService.someValue;
}
}
@Component({})
export class ChildComponent extends ParentComponent{
constructor(){
super();//ERROR: Expected 1 arguments, but got 0
console.log(this.value);//I expect child to have this as well
}
}
您也应该向您的孩子注入相同的服务(基本上您是在进行继承,即父子类关系,即OOD)
@Component({})
export class ChildComponent extends ParentComponent{
constructor(someService: SomeService){
super(someService);//ERROR: Expected 1 arguments, but got 0
console.log(this.value);//I expect child to have this as well
}
}
请注意:这里您不是在创建您正在执行的childcomponent,即继承parentcomponent并扩展它
如果希望它成为父子组件关系(在html中,即父标记下的子标记),则不应在子标记中扩展父组件(不需要继承),因此代码如下所示
@Component({})
export class ParentComponent{
protected value: any;
constructor(someService: SomeService){
this.value = someService.someValue;
}
}
@Component({})
export class ChildComponent {
constructor(someService: SomeService){
super();
console.log(this.someService.value);
}
}
请使用
@输入和@Output
解码
此链接将帮助您
super()
的孩子身上发现了错误,因为家长构造函数需要一个参数(实际的服务注入)