目前,我在angular 2中工作,从后端映射数据后出现错误,并尝试调用函数。下面的错误文字
类型为“ {date:Date;食谱:Recipe []; } []'不能分配给'Day []'类型的参数。
Day模型如下:
import { Recipe } from "../recipes/recipe.model";
export class Day {
public date: Date;
public recipes :Recipe[]
constructor(date: Date, recipes ?: Recipe[]) {
this.date = date;
this.recipes = recipes;
}
getDate(){
return this.date;
}
}
setDays方法发生错误,传递的参数无效。
loadDays() {
return this.http.get<Day[]>(
this.urlDays,
).pipe(
map((days => {
return days.map(day => {
return {
...day,
recipes: day.recipes ? day.recipes : []
};
});
})),
tap(days => {
this.daysService.setDays(days);
}),
);
}
在这部分代码中:
return {
...day,
recipes: day.recipes ? day.recipes : []
};
我检查是否有配方的食谱数据,如果没有食谱,则添加配方类型为空的数组。
DaysService代码:
import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
import { Day } from "./day.model";
@Injectable()
export class DaysService {
private startDate: Date = new Date(new Date().getTime());
private dayLongInMS: number = 86400000;
private daysShown: Array<Day> = [];
daysChanged = new Subject<Day[]>();
getDays() {
return this.daysShown.slice();
}
setDays(days: Day[]) {
this.daysShown = days;
this.daysChanged.next(this.daysShown.slice());
}
我认为我需要一种方法来将这两个参数归为一组,然后将其划分为运算符三点(日期:日期;食谱:Recipe [];)为一个(Day [] )属性。
我在这里发现类似的问题: Argument of type {...} is not assignable to parameter of type [ ] 但是我不知道该如何使用它。你能给我一些建议吗?
答案 0 :(得分:1)
您不返回Day
类的实例。 http客户端不会仅仅因为将它们指定为通用类型而创建Day
实例。而且编译器在抱怨,因为您创建的对象不符合Day
类的接口。
相反,您将需要在Day
运算符中创建map
实例。
loadDays() {
return this.http.get(this.urlDays).pipe(
map((response: any) => {
return response.map(day => new Day(day.date, day.recipes || []));
}),
tap(days => {
this.daysService.setDays(days);
}),
);
}
如果要确保Day
实例始终使用非空的recipes
初始化,则应在构造函数中进行处理,而不要依赖于调用代码。
export class Day {
public date: Date;
public recipes :Recipe[]
constructor(date: Date, recipes ?: Recipe[]) {
this.date = date;
this.recipes = recipes || [];
}
getDate(){
return this.date;
}
}