类型"any[]"不能用作索引类型 角度构建



当我使用ng serve时,一切正常。当我使用ng serve --prod --aot时,它会抱怨Type 'any[]' cannot be used as an index type.我找不到任何可以解决它的东西。它似乎指的是 Tags 变量type any[]因为当我将其注释掉时,一切都会编译。

以下是相关代码:

//cluster-details.component.ts
...
export class ClusterDetailsComponent implements OnInit {
infoTitles = {
edgeNodePublicDNS: 'Edge Node Public DNS',
...
tags: 'Tags'
};
infoKeys: string[];
info: any;
tags: any[];
...
this.requestsService.emrinstanceDetailsGET(body)
.subscribe(
(data) => {
this.infoKeys = Object.keys(data);
this.info = data;
...

cluster-details.component.html:

<tr *ngFor="let key of infoKeys">
<td>
<strong>{{ infoTitles[key] }}:</strong>
</td>
<td>
{{info[key]}}
</td>
</tr>
<tr>
<td>
<strong>{{ infoTitles[tags] }}:</strong>
</td>
<td>
{{tags}}
</td>
</tr>

请求返回如下数据:

.map(
(response: Response) => {
const data = response.json();
return data['clusterDetail'];

现在我知道'只是不要让它打any[],但我不知道该怎么做。返回的是一个 JSON 值,它只是一个对象类型。将类型更改为对象不起作用,我没有看到任何其他有效的类型。也许我必须为它制作一个界面?

我相信这里的AOT无法解析您的"infoTitles",因为您没有给它一个特定的类型,而是使用了"infoTitles[key]",对象[名称](AOT理所当然地认为您正在使用数组语法)后来导致了编译错误。可能的解决方案:

infoTitles: InfoTitle = {
edgeNodePublicDNS: 'Edge Node Public DNS',
...
tags: 'Tags'
};

您需要创建一个类:

export class InfoTitle {
edgeNodePublicDNS: string;
...
tags: string;
}

想通了。我无意的变量的简单误用:

HTML 行...{{ infoTitles[tags] }}...正在尝试使用标签变量索引 infoTitle - 我的意思是这是一个只是"标签"的字符串,它将正确引用我需要的 infoTitle 值。但是我没有发现我正在使用标签数组。因此,修复应该只使用像tagIndexString = 'tags'这样的字符串或变量,然后就可以...{{ infoTitles[tagIndexString] }}...HTML

在我的场景中,由于以下代码错误,同样的错误被"ng serve">命令忽略:

给出错误的代码:

<span data-toggle="tooltip" title={{subData[[col.field]]}}>{{subData[[col.field]]}}</span>

更改了代码以解决错误:

<span data-toggle="tooltip" title={{subData[col.field]}}>{{subData[col.field]}}</span>

只需从"[["中删除额外的"[",如果您的 html 代码有的话。

最新更新