【问题标题】:Using key name to index json object gives error [[keyname]] can't be used to index type 'Object'使用键名索引 json 对象给出错误 [[keyname]] 不能用于索引类型“对象”
【发布时间】:2021-08-12 18:20:19
【问题描述】:

我从新闻 api 获取新闻,示例响应如下。当我尝试访问文章时,行 data['articles'] 会生成以下错误-

元素隐含地具有“任何”类型,因为“文章”类型的表达式不能用于索引类型“对象”。 “对象”类型上不存在属性“文章”。

{
"status": "ok",
"totalResults": 11814,
-"articles": [
-{
-"source": {
"id": "engadget",
"name": "Engadget"
},
"author": "https://www.engadget.com/about/editors/richard-lawler",
"title": "Tesla 'suspends' Bitcoin car purchases citing environmental impact",
"description": "You can't buy a Tesla with Bitcoin anymore..",
"url": "https://www.engadget.com/elon-musk-bitcoin-221708146.html",
"urlToImage": "https://s.yimg.com/os/creatr-uploaded-images/2021-05/a0f90c30-b36f-11eb-aff6-04fb28cf2f4b",
"publishedAt": "2021-05-12T22:17:08Z",
"content": "Just weeks after Tesla started accepting Bitcoin as currency for cars, Elon Musk revealed in a tweet that it will \"suspend\" the effort. According to the release (Tesla does not appear to have a funct… [+768 chars]"
},......
}

服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';


@Injectable({
  providedIn: 'root'
})
export class NewsApiService {

  apiKey='f635258abaf9455c876874a78a5ca745';
  url='https://newsapi.org/v2/everything?q=trading&'+'apiKey=f635258abaf9455c876874a78a5ca745';
  constructor(private http:HttpClient) { }
  public getNews()
  {
    return this.http.get(this.url);
  }
}

ts 文件

import { Component, OnInit } from '@angular/core';
import{NewsApiService} from 'src/app/services/news-api.service';
@Component({
  selector: 'app-newsfeed',
  templateUrl: './newsfeed.component.html',
  styleUrls: ['./newsfeed.component.css']
})
export class NewsfeedComponent implements OnInit {

  articlelist:any;
  constructor(private apiService:NewsApiService) { }

  ngOnInit(): void {

    this.apiService.getNews().subscribe((data)=>{console.log(data);
    this.articlelist=data['articles']})

    
  }

}

【问题讨论】:

    标签: json angular typescript rest


    【解决方案1】:

    您的 http.get 默认返回 Object 类型。你应该对它进行类型转换。现在any 可以工作,但我建议为您的类型创建一个特定的接口:

      public getNews()
      {
        return this.http.get<any>(this.url);
      }
    

    (可选) 根据您的打字稿配置的严格程度,您可能还需要将其添加到您的回调中:

    this.apiService.getNews().subscribe((data: any)=>{console.log(data);
    

    【讨论】:

      猜你喜欢
      • 2018-04-01
      • 2021-02-22
      • 1970-01-01
      • 2017-06-11
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      相关资源
      最近更新 更多