简体   繁体   English

Angular 将数组分配给另一个数组时出现未定义错误

[英]Angular undefined error when assigning array to another array

So in this component, i am getting an array of objects from the parent component, which i use to display a list of objects, but when i create a new array, and assign the first array to it and try to work with it, i get an error that the new array is undefined, here's my code:所以在这个组件中,我从父组件获取了一个对象数组,我用它来显示一个对象列表,但是当我创建一个新数组并将第一个数组分配给它并尝试使用它时,我收到新数组未定义的错误,这是我的代码:

export class AdherentsListComponent implements OnInit {
  // adherents: Adherent[];
  adherent: Adherent;

  @Input() adherents: Adherent[];

 
  constructor(private adherentService: AdherentService, private alertify: AlertifyService, private router: Router,private modalService: NgbModal) { }

  ngOnInit() {
  }
  
   tempAdherents = this.adherents; //this is what's not working

   loadAdherent(id){
    this.adherentService.getAdherent(id).subscribe((adherent: Adherent) => {
      this.adherent = adherent;
    }, error => {
      this.alertify.error(error);
    })
  }

}

Please any idea how can i create the new array, Thank you.请知道如何创建新数组,谢谢。

Try to initzialize your input like @Input() adherents: Adherent[] = [] as Adherent[];尝试初始化您的输入,例如 @Input() 追随者: Adherent[] = [] as Adherent[];

You are missing a declaration for tempAdherents .您缺少tempAdherents的声明。

export class AdherentsListComponent implements OnInit {
  // adherents: Adherent[];
  adherent: Adherent;

  @Input() adherents: Adherent[];

 
  constructor(private adherentService: AdherentService, private alertify: AlertifyService, private router: Router,private modalService: NgbModal) { }

  ngOnInit() {
  }
  
   var tempAdherents = this.adherents; //this is what's not working

   loadAdherent(id){
    this.adherentService.getAdherent(id).subscribe((adherent: Adherent) => {
      this.adherent = adherent;
    }, error => {
      this.alertify.error(error);
    })
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM