【问题标题】:Angular: Argument of type is not assignable to parameter of.. and property "id" is missing in typeAngular:类型的参数不可分配给..的参数,并且类型中缺少属性“id”
【发布时间】:2020-10-23 16:07:39
【问题描述】:

感谢您查看此问题。我对 Angular 很陌生,我有一个我无法弄清楚的问题。我正在做一件小事,为了练习,添加带有复选框的文本。但是,我还没有做到这一点。它失败并出现错误:

Eerror TS2345: Argument of type '{ title: string; done: false; }' is not assignable to parameter of type '{ id: number; title: string; done: boolean; }'.

Property 'id' is missing in type '{ title: string; done: false; }'.

代码是task-list.component.ts

这是我的 ts 文件。如果您需要更多信息,请告诉我。我现在一头雾水!谢谢

import {Component, ViewEncapsulation} from '@angular/core';

@Component({
  selector: 'mac-task-list',
  templateUrl: './task-list.component.html',
  encapsulation: ViewEncapsulation.None
})
export class TaskListComponent {
  tasks = [
    {id: 1, title: 'Task 1', done: false},
    {id: 2, title: 'Task 2', done: true}
  ];

  addTask(title: string) { // fails here
    this.tasks.push({
      title, done: false
    });
  }
}

【问题讨论】:

  • 你推送的地方,你还需要一个id..这就是抱怨..
  • 谢谢,我不知道如何将 id 放入推送中。我能看到的任何地方都有 sn-p 代码吗?我所做的一切都不起作用。

标签: angular components


【解决方案1】:

你需要添加缺少的道具:

为了测试目的,创建一个计数器来生成一个 id 值:

countId = 0;
//...

addTask(title: string) { // fails here
    this.tasks.push({
      id: this.countId++,
      title, done: false
    });
  }

否则将 id 属性声明为可选属性。

【讨论】:

  • 谢谢,但我仍然不知道该怎么做。我一直在寻找,却一无所获。对不起。
  • 为了测试目的,添加一个计数器来生成 id 值。查看更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
  • 2019-07-20
  • 2023-03-09
  • 2017-12-05
  • 1970-01-01
  • 2019-06-24
  • 2021-06-14
相关资源
最近更新 更多