TS为什么引发此错误“无法将类型'MyMedicine []'的参数分配给类型'MyMedicine'的参数”?

时间:2020-09-29 10:15:33

标签: angular typescript observable mean-stack

我有一个界面:

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。

2 个答案:

答案 0 :(得分:0)

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

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

medicines: MyMedicines[];

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

答案 1 :(得分:0)

由于HTTP发布请求仅将新添加的项返回到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请求发出的可观察对象,如下所示:

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

请从您的身边检查是否正常。