Angular 访问深嵌套子组件中的数组

Angular 访问深嵌套子组件中的数组,angular,ionic3,Angular,Ionic3,我想知道如何访问childscomponent数组,结构如下: parent.component.ts->child.component.ts->child.component2.ts 在child.component2.ts中,我有一个数组,我想在main.component中访问它。这是通过设置模板变量实现的,还是需要使用输出()?您可以在主组件构造函数方法中插入子组件2 子组件2.ts getUniqueArray(){ return [1,2,3,4,5]; } construct

我想知道如何访问childscomponent数组,结构如下:

parent.component.ts->child.component.ts->child.component2.ts


在child.component2.ts中,我有一个数组,我想在main.component中访问它。这是通过设置模板变量实现的,还是需要使用
输出()

您可以在主组件构造函数方法中插入子组件2

子组件2.ts

getUniqueArray(){
  return [1,2,3,4,5];
}
constructor(private child2: ChildComponent2){
   this.child2.getUniqueArray();
}
main.component.ts

getUniqueArray(){
  return [1,2,3,4,5];
}
constructor(private child2: ChildComponent2){
   this.child2.getUniqueArray();
}

解决此问题的另一种方法是创建包含数组变量的服务,然后将其注入main.component.ts和child.component.ts

export class MainComponent {
  constructor(private customService: CustomService) {}
  myArr = this.customService.myArray;
}
export class MainComponent {
  constructor(private customService: CustomService) {}
  myArr = this.customService.myArray;
}
定制服务

@Injectable() 
export class CustomService {
 myArray = [1,2,3,4];
}
main.component.ts

export class MainComponent {
  constructor(private customService: CustomService) {}
  myArr = this.customService.myArray;
}
export class MainComponent {
  constructor(private customService: CustomService) {}
  myArr = this.customService.myArray;
}
child2.component.ts

export class MainComponent {
  constructor(private customService: CustomService) {}
  myArr = this.customService.myArray;
}
export class MainComponent {
  constructor(private customService: CustomService) {}
  myArr = this.customService.myArray;
}