【发布时间】:2021-11-14 18:07:44
【问题描述】:
我在 Angular 上看 YouTube 上的培训视频,不管是什么代码,都会有很多错误。 下面是从服务器获取数据的方法。
getAll() {
return this.http.get(`${environment.fbDbUrl}/products.json`)
.pipe( map ( res => {
return Object.keys(res)
.map( key => ({
...res[key],
id: key,
date: new Date(res[key].date)
}))
}))
}
这里
res[key],
然后res[key].date
返回错误
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object'. No index signature with a parameter of type 'string' was found on type 'Object'.
如何解决这个问题? 本次请求要接收的json格式数据:
{
"date" : "2021-11-11T13:46:32.056Z",
"info" : "<h2>The main</h2><p>A type smartphone</p><p>Operating system Apple iOS</p><p>Operating system version iOS 13</p><p>Screen size 5.8\"</p><p>Screen resolution 1125x2436</p><p>RAM 3 GB</p><p>Flash memory 128 GB</p><p>Integrated camera 12MP + 12MP</p><p>Number of main cameras 2</p>",
"photo" : "<p><img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDA................
oHxB/9k=\"></p>",
"price" : "11700",
"title" : "Iphone X 128GB",
"type" : "Phone"
}
我创建了一个接口来描述数据
export interface ProductData {
"date" : string,
"info" : string,
"photo" : string,
"price" : string,
"title" : string,
"type" : string
}
修正方法:
getAll() {
return this.http.get(`${environment.fbDbUrl}/products.json`)
.pipe( map ( (res as ProductData) => {
return Object.keys(res)
.map( key => ({
...res[key],
id: key,
date: new Date(res[key].date)
}))
}))
}
但现在它在这一行给(res as ProductData) 一个错误:
TS2345: Argument of type 'ProductData' is not assignable to parameter of type '(value: Object, index: number) => unknown'. Type 'ProductData' provides no match for the signature '(value: Object, index: number): unknown'.
【问题讨论】:
-
向我们展示此调用应返回的 json 数据。
-
使用打字稿,有很多错误不是真正的错误,而是由于类型未被正确识别而抛出。你的错误到底在哪里?我怀疑它可能在调用此路由并实际获取数据后在组件端?
-
这个错误是IDEA编译器给出的。我只是在学习 TypeScript,我无法确定它有多重要。不知道是否可以忽略,或者代码是否需要更正使其不存在。
标签: angular typescript