首页 > 解决方案 > 为什么角度不允许我为对象赋值?

问题描述

我做了一个查询组件来查询数据库中的一个人,它有一个按钮来编辑那个特定的人,当它被点击然后切换到另一个组件来编辑这个人,所以我添加了一个按钮再次返回到查询更新数据的组件显示在查询组件上,但是在它返回的那一刻,查询组件没有出现。

我尝试使用服务传递数据,这是代码的一部分:

export class PersonaGetComponent implements OnInit {

personas: Persona[];
individuo: {cedula: string, direccion: string; nombre: string; _id: string};
valor: any;

constructor(private ps: PersonasService, private vd: VolverDataService) { }

ngOnInit() {
  this.ps
  .getPersonas()
  .subscribe((data: Persona[]) => {
   this.personas = data;
});

if (this.vd.volver === true) {
  console.log(this.individuo);
  this.valor = this.vd.cedula;
  this.individuo.cedula = this.vd.cedula;  //this part shows an error, it says that individuo is undefined so I cannot assign a value
  this.individuo.direccion = this.vd.direccion;
  this.individuo.nombre = this.vd.nombre;
 }
}

这是错误:

无法设置未定义的属性“cedula”

个体对象未定义,我无法为其分配任何值。

标签: angulartypescript

解决方案


您只定义了Typeofindividuo但从未为其赋值。这就是为什么控制台对你大喊变量是undefined. 改为这样做:

// Change:
individuo: {cedula: string, direccion: string, nombre: string, _id: string};
// With this:
individuo = {cedula: '', direccion: '', nombre: '', _id: ''};

推荐阅读