【问题标题】:Angular - Service ComponentAngular - 服务组件
【发布时间】:2021-09-13 05:19:17
【问题描述】:

元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{}”。 在类型“{}”.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);
        
      })
    )
  }
}

【问题讨论】:

    标签: angular components


    【解决方案1】:

    您收到此错误是因为您将值动态分配给未明确标记类型的 raw。这可以通过使用任何类型显式标记 raw 来解决。改变

    let raw = {}
    

    到

     let raw:any = {}
    

    这将是一个快速修复。使用正确类型的更好修复。像这样为原始对象创建类型

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

    这里我们为具有字符串键和值的对象创建一个类型,它将是 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,
    }
    

    【讨论】:

    • 另外,如果您知道result 是一个字符串,请使用map((result:string)=>{...}
    猜你喜欢
    • 1970-01-01
    • 2019-06-15
    • 2018-08-22
    • 2020-12-28
    • 2018-05-20
    • 2016-03-25
    • 2020-08-05
    • 1970-01-01
    • 2017-05-26
    相关资源
    最近更新 更多