export class ListService {
...
getAllLists(): Observable<List[]> {
let URI = `${this.serverApi}/bucketlist/`;
return this.http.get<List[]>(URI)
.pipe(
map(res => <List[]>res.lists)
);
}
}
用ng serve
编译时,显示如下错误
错误 TS2339:属性“lists”在类型“List[]”上不存在。
已知res.lists
是List[]
类型。为 res
定义属性以便代码编译无误的更好方法是什么?
这是一个res
样本
{
"success": true,
"lists": [
{
"_id": "5c6673abeb64adb41ec6dfaf",
"title": "First Project"
}
]
}
尝试的解决方案
interface Response {
success: boolean;
lists: List[];
}
export class ListService {
getAllLists(): Observable<List[]> {
...
return this.http.get<Response>(URI)
.pipe(
map(res => res.lists)
);
}
}
最佳答案
长话短说
res
看起来像一个对象,而不是 List[]
.所以http.get<List[]>
行不通。
试试这个
interface MyResponse {
success: boolean;
lists: List[];
}
export class ListService {
...
getAllLists(): Observable<List[]> {
let URI = `${this.serverApi}/bucketlist/`;
// Replace 'List[]' with 'MyResponse' here
return this.http.get<MyResponse>(URI)
.pipe(
map(res => res.lists)
);
}
}
说明
当你写 this.http.get<List[]>(URI)
您的编译器期待类型为 Array of List
的响应强>。问题是响应与签名不匹配。正如你所说res
看起来更像
{
"success": true,
"lists": [
{
"_id": "5c6673abeb64adb41ec6dfaf",
"title": "First Project"
}
]
}
您可以看到它不是一个数组,所以 List[]
行不通
关于angular - 在 Typescript 中定义一个属性以防止 Angular 中的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54745876/