无法将对象推入数组

时间:2018-07-08 20:53:19

标签: angular

我的Angular toDoApp项目有问题。我有3个组件(app,task-form.task-list)。应用程序组件从其他组件接收最终逻辑。但是,当我尝试将最终对象推入数组时,它表示对象值未定义。

   export interface  toDoInterface {
        tittle: string,
        description:string;
    }

 ----------

 export class AppComponent {

  toDoList = [];      //**It returns undefined value**

  newToDo (formData: toDoInterface) {
    this.toDoList.push({
    tittle: formData.tittle,
    description: formData.description
  });  
 }
}

----------

  export class TaskFormComponent implements OnInit {

 @Output() toDo = new EventEmitter<{newTittleValue: string, newDescValue:string}>();

  tittleValue = '';
  descValue = '';

  constructor() { }

  ngOnInit() {
  }

  addToList () {

  this.toDo.emit({newTittleValue:this.tittleValue,newDescValue:this.descValue})

  }  
}


----------

export class TaskListComponent implements OnInit {

 @Input() name: toDoInterface;

  constructor() { }

  ngOnInit() {
  }

}

1 个答案:

答案 0 :(得分:2)

您要发射的物体与您希望在app.component.ts文件newToDo方法中接收的物体不同。

您发射以下对象:

{
  newTittleValue: string;
  newDescValue: string;
}

但是,当您将其添加到列表中时,您将使用以下结构(在您的情况下为toDoInterface接口):

{
  tittle: string;
  description: string;
}

您要使用传入的formData对象中不存在的参数。

解决方案很简单。将界面用作EventEmitter的类型。

像这样:

@Output() toDo = new EventEmitter<toDoInterface>();

tittleValue = '';
descValue = '';    

addToList() {
  this.toDo.emit({ tittle: this.tittleValue, description: this.descValue });
}

我还制作了stackblitz project,因此您可以看到它的运行情况。

相关问题