无法将 HTTP 响应映射到 angular 5 中的接口类型

Cannot map HTTP response to interface type in angular 5

我正在调用 HTTP 请求,并在服务中使用接口将接收到的响应转换为所需类型。 HTTP 响应是一个 JSON 对象,其中包含一些项的键值对。我已经在组件中订阅了该服务。当我控制台记录在订阅函数中收到的响应时,它会使用键值对完美地记录对象。但是当我将该对象分配给组件 class 成员时,它似乎没有被类型转换为所需的接口类型。因为当我在组件 html 中使用 class 成员变量键时,我得到错误 - 'Cannot read 属性 'X' of undefined'

这是代码片段 -

界面

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);
    }
}

component.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",
      }
   ]
}

在上述代码的情况下,我收到错误 - "Cannot read property 'articles' of undefined"。为什么即使在使用接口类型转换 HTTP 响应时我也会收到此错误?

我认为您需要为您的用例使用安全导航运算符 ?,如下面的代码 -

<div *ngFor="let item of newsData?.articles">
    {{item.description}}
</div>

safe navigation operator ? Angular 中的运算符可以避免在应用程序中不存在 parent/base 值的情况下抛出任何错误,并且在以下情况下也非常有用异步绑定

您正在尝试在解决之前访问数据
在这种情况下,使用 safe navigation operator ( ?. )
在访问对象的属性时,如果对象为 null 或未定义,则可能会抛出异常。 Angular 安全导航运算符 (?.) 是防止 属性 路径中出现空值和未定义值的一种流畅且方便的方法。

<ng-container *ngIf="newsData">
    <div *ngFor="let item of newsData?.articles">
        {{item.description}}
    </div>
<ng-container>