【发布时间】: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