Angular-服务组件



元素隐式具有"any"类型,因为类型为"string"的表达式不能用于索引类型"{}"。在类型"{}"上找不到具有"string"类型参数的索引签名。ts(7053(

正在获取上述错误消息。在这方面需要帮助。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { GlobalDataSummary } from '../models/gloabl-data';
@Injectable({
providedIn: 'root'
})
export class DataServiceService {
private globalDataUrl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/01-01-2021.csv'
constructor(private http : HttpClient) { }
getGlobalData(){
return this.http.get(this.globalDataUrl, {responseType :'text'}).pipe(
map(result=>{
let data: GlobalDataSummary[] = [];
let raw = {}
let rows = result.split('n');
rows.splice(0 , 1);
//console.log(rows);
rows.forEach(row=>{
let cols = row.split(/,(?=S)/)

let cs = {
country : cols[3],
confirmed : +cols[7],
deaths : +cols[8],
recovered : +cols[9],
active : +cols[10],
};
let temp = raw[cs.country];
if(temp)
{
temp.active = cs.active + temp.active
temp.confirmed = cs.confirmed + temp.confirmed
temp.deaths = cs.deaths + temp.deaths
temp.recovered = cs.recovered + temp.recovered
raw[cs.country] = temp;
}else{
raw[cs.country] = cs;
}



})


return Object.values(raw);

})
)
}
}

您之所以会出现此错误,是因为您正在将值动态分配给未显式标记其类型的原始值。这可以通过用任何类型显式标记原始来解决。更改

let raw = {}

let raw:any = {}

这将是一个快速的解决方案。使用正确的打字法是一个更好的办法。为原始对象创建类型,如

interface Raw {
[key: string]: CS;
} 

在这里,我们为对象创建一个类型,它将具有字符串键,vales将是CS类型。CS是您试图分配给raw的内容。你可以根据自己的选择来命名它。以下是CS的类型。

interface CS {
country: string;
confirmed : number,
deaths : number,
recovered : number,
active : number,
}

分配类型如下:

let raw: Raw = {};

//这不会失败。这只是一个应该有效的例子。

raw['India'] = {
country: 'India',
confirmed : 22,
deaths : 0,
recovered : 22,
active : 0,
}

最新更新