将从注入父级构造函数的服务接收的值传递给子组件

时间:2018-04-19 06:15:49

标签: angular

为孩子和父母注入服务的Angular方式是什么?最初的想法是为所有子组件设置和共享类字段。我在子组件上收到错误Expected 1 arguments, but got 0。我找到了approach to make child @Injectable,但它违反了@Component行为。

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

2 个答案:

答案 0 :(得分:1)

你也应该为你的孩子注入相同的服务(基本上你做的是继承,即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
   }
}

仅用于注释:此处您没有创建正在执行的子组件,即继承父组件并对其进行扩展。

如果你想要父子组件关系(就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);
   }
}

答案 1 :(得分:0)

请使用 SELECT user_time.weeks_ago, SUM(COUNT(distinct user_time.user_id)) OVER (ORDER BY weeks_ago desc ROWS UNBOUNDED PRECEDING) as test FROM (SELECT FLOOR(EXTRACT(DAY FROM sysdate - ev.time) / 7) AS weeks_ago ,ev.user_id as user_id FROM events as ev WHERE ev.action='some_user_action' ) user_time GROUP BY user_time.weeks_ago decoretor

此链接可以帮助您