【问题标题】:Angular undefined error when assigning array to another array将数组分配给另一个数组时出现角度未定义错误
【发布时间】:2020-07-21 20:36:06
【问题描述】:

所以在这个组件中,我从父组件中获取了一个对象数组,我用它来显示一个对象列表,但是当我创建一个新数组并将第一个数组分配给它并尝试使用它时它,我得到一个新数组未定义的错误,这是我的代码:

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);
    })
  }

}

请知道如何创建新数组,谢谢。

【问题讨论】:

  • 您是否检查以确保您正确地为 html 中的 @Input 属性提供了一个值? <AdherentsList [adherents]="someArray">
  • @Zze 是的,数组被传递,我将它显示在表格中,这是我不能使用的新数组

标签: javascript arrays angular typescript


【解决方案1】:

尝试像 @Input() 一样初始化您的输入:Adherent[] = [] as Adherent[];

【讨论】:

  • 我做了,但不幸的是它没有改变任何东西
【解决方案2】:

您缺少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);
    })
  }
}

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多