【发布时间】:2018-10-31 22:03:38
【问题描述】:
我正在调用 HTTP 请求,并在服务中使用接口将接收到的响应类型转换为所需类型。 HTTP 响应是一个带有一些键值对项的 JSON 对象。我已经在一个组件中订阅了该服务。当我控制台记录订阅函数中收到的响应时,它会使用键值对完美地记录对象。但是当我将该对象分配给组件类成员时,它似乎没有被强制转换为所需的接口类型。因为当我在组件 html 中使用类成员变量键时,我得到错误 - 'Cannot read property 'X' of undefined'
这里是代码 sn-ps -
界面
export interface NewsItem {
status: string;
totalResults: number;
articles: any[];
}
服务
export class NewsService {
constructor(private http: HttpClient) {}
getCategoryNews(): Observable<NewsItem>{
return this.http.get<NewsItem>(newsUrl);
}
}
组件.ts
export class NewsContainerComponent implements OnInit {
newsData: NewsItem;
constructor(private _newsService: NewsService) {}
ngOnInit() {
this._newsService.getCategoryNews().subscribe(
(response) => {
this.newsData = response;
console.log(this.newsData);
},
(err) => {
console.error(err);
}
)
}
}
component.html
<div *ngFor="let item of newsData.articles">
{{item.description}}
</div>
HTTP请求的实际响应如下
{
"status":"ok",
"totalResults":2,
"articles":[
{
"source":{
"id":"google-news-au",
"name":"Google News (Australia)"
},
"title":"Former Malaysian PM questioned on graft",
"description":"Former Malaysian Prime Minister Najib Razak could face criminal charges after being questioned over a corruption scandal."
},
{
"source":{
"id":"the-guardian-uk",
"name":"The Guardian (UK)"
},
"title":"Manchester Arena attack: thousands to mark anniversary",
"description":"Series of events across city including a mass singalong are being held one year on from terrorist attack",
}
]
}
在上述代码的情况下,我收到错误 - “无法读取未定义的属性'文章'”。为什么即使在使用接口类型转换 HTTP 响应时也会出现此错误?
【问题讨论】:
标签: angular angular-httpclient