【问题标题】:Why is TS throwing this error "Argument of type 'MyMedicine[]' is not assignable to parameter of type 'MyMedicine'."?为什么 TS 会抛出此错误“'MyMedicine []' 类型的参数不可分配给'MyMedicine' 类型的参数。”?
【发布时间】:2020-09-29 10:15:33
【问题描述】:

我有一个界面:

export interface MyMedicine {
_id: String;
name: String;
quantity: Number;
time: String;

}

这是我发布数据的角度服务:

postMed(newMed): Observable<MyMedicine[]>{
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post<MyMedicine[]>(`${this.url}/api/medicine`, newMed, {headers:headers});

}

这是我的 addmedicine() 组件,用于在提交表单时发布数据:

addmedicine(){
const newMedicine = {
  name: this.name,
  quantity: this.quantity,
  time: this.time
};
this.medService.postMed(newMedicine)
    .subscribe(medicine =>{
      this.medicines.push(medicine);
    })}

我收到一条错误消息,提示“'MyMedicine[]' 类型的参数不可分配给 'MyMedicine' 类型的参数。 类型“MyMedicine[]”缺少类型“MyMedicine”中的以下属性:_id、名称、数量、时间”

我已经在我的组件中导入了接口和服务。依赖注入已被处理。 _id 是 MongoDB 生成的默认 id。

【问题讨论】:

  • 你可以试试this.medicines = [...this.medicines, ...medicine] 吗?
  • @VLAZ 正好相反。 postMed 返回一个元素数组,this.medicines.push 需要一个元素。
  • @Emilien 我试过你的方法,我得到一个错误“类型'MyMedicine []'缺少类型'MyMedicine'的以下属性:_id,名称,数量,时间”

标签: angular typescript observable mean-stack


【解决方案1】:

正如我们在上面的 cmets 中告诉您的,问题是您从 this.medService.postMed 收到了一个 MyMedicine 数组。

其中一种解决方案是仅添加您收到的数组中的最后一项。

medicines: MyMedicines[];

this.medService.postMed(newMedicine).subscribe(medicines => this.medicines.push(medicines.pop()))

【讨论】:

  • 谢谢@Emilien。现在没有错误,但数据库没有任何更新。我已经在 Postman 中测试了我的 API,它可以工作。
【解决方案2】:

由于 HTTP post 请求只返回新添加的项目到 MyMedicines[] 数组修改 postMed 方法如下:

postMed(newMed): Observable<MyMedicine>{
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post<MyMedicine>(`${this.url}/api/medicine`, newMed, {headers:headers});

然后在组件类中,使用 HTTP post 请求发出的 observable,如下所示:

addmedicine(){
const newMedicine = {
  name: this.name,
  quantity: this.quantity,
  time: this.time
};
this.medService.postMed(newMedicine)
    .subscribe((medicine : MyMedicine) =>{
      this.medicines.push(medicine);
    })}

请从你身边检查它是否正常工作。

【讨论】:

    猜你喜欢
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多