【发布时间】:2021-04-11 07:17:22
【问题描述】:
在我的 Angular 应用程序中,API 调用的响应存在问题:
private async getActor(actor:string) {
const response = await this.searchActor.getActorImage(actor).toPromise()
let actPics = []
for (var val of (response as any[]).value) {
actPics.push(val.thumbnailUrl)}
}
我的应用程序运行良好,但是当我运行 ng serve 时控制台中出现此消息
错误: src/app/quiz-editor/actor-question/actor-question.component.ts:55:41 - 错误 TS2551:类型“任何 []”上不存在属性“值”。你是否 意思是“价值观”?
55 for (var val of (response as any[]).value) { ~~~~~
node_modules/typescript/lib/lib.es2015.iterable.d.ts:75:5 75 个值():可迭代迭代器; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 'values' 在这里声明。
当我console.log(response) 我得到:
我做了一些研究,读到我应该声明response,但我应该怎么做呢?
我试过这个解决方案:
private async getActor(actor:string) {
const response: { value:any[] } = await this.searchActor.getActorImage(actor).toPromise()
let actPics = []
for (let val of response.value) {
actPics.push(val.thumbnailUrl)}
}
但现在我有这个错误:
Error: src/app/quiz-editor/actor-question/actor-question.component.ts:55:11 - error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Property 'value' is missing in type 'Object' but required in type '{ value: any[]; }'.
55 const response: { value:any[] } = await this.searchActor.getActorImage(actor).toPromise()
~~~~~~~~
src/app/quiz-editor/actor-question/actor-question.component.ts:55:23
55 const response: { value:any[] } = await this.searchActor.getActorImage(actor).toPromise()
~~~~~
'value' is declared here.
【问题讨论】:
-
你需要给
response添加类型 -
以同样的方式声明其他任何内容
const response: { value: any[] } = ...或其他任何内容。见Type definition in object literal in TypeScript -
searchActor.getActorImage的签名是什么?它与@tilo 建议的响应类型冲突 -
这似乎不正确
for (var val of (response as any[]).value)。 Array 类型没有value属性,你确定这里没有弄错吗 -
将
for (var val of (response as any[]).value) {这一行改为for (var val of (response as any).value) {
标签: angular typescript