Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 传递从注入到父级的服务接收的值';子组件的构造函数_Angular - Fatal编程技术网

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
解码

此链接将帮助您


它的继承不是父子关系我不需要@Input。我需要向父级注入服务,并从该服务中获取价值。但是我在使用
super()
的孩子身上发现了错误,因为家长构造函数需要一个参数(实际的服务注入)