【问题标题】:Cannot map HTTP response to interface type in angular 5无法将 HTTP 响应映射到角度 5 中的接口类型
【发布时间】: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


    【解决方案1】:

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

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

    Angular 中的安全导航运算符 ? 运算符,可避免在应用程序中不存在父/基值的情况下引发任何错误,并且在异步绑定的情况下也非常有用

    【讨论】:

    • @Pradeep,谢谢。我认为您无法初始化界面中的字段,因此无法在界面中编写'articles:any [] = []',因为我已经检查过了。但是在 ngFor 中写 'newsData?.articles' 消除了错误。但是你能解释一下吗?究竟是什么?运营商在这种情况下呢?另外,如果我在模板中使用对象(newsData)的所有字段,我是否需要这样做? HTTP响应不是首先转换为接口类型吗?
    • ?。可用于吸收属性链中的空引用。使用它代替点存取器。在基值可能为 null 或未定义的情况下。
    • @AbhinandanKhilari 我不确定intialize filed in interface,但是是的? 在Angular 中被称为安全导航运算符,可以避免在父/基值不存在的情况下抛出任何错误给你应用程序,在异步绑定的情况下也非常有用。
    • @user1608841 是的,很好解释!!
    【解决方案2】:

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

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

    【讨论】:

    • 谢谢。我认为安全导航运算符是在 angular 中引入的,而在 angularjs 中没有,对吧?顺便说一句,在模板中使用属性未定义对象时,angularjs没有任何问题,对吧?
    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 2020-11-23
    • 2018-03-07
    • 2021-12-03
    • 2011-01-10
    • 2020-01-28
    • 1970-01-01
    • 2016-06-05
    相关资源
    最近更新 更多