首页 > 解决方案 > Angular 6:接收对象并解析它的问题

问题描述

我从 webAPI 收到

return Ok(new List<DomainBO>() { userDomain });

我通过 stringyfy 得到这个对象:

[
  {
    "id": 281,
    "domainName": "MTH",
    "domainTypeId": 2,
    "domainTypeName": "Carrier"
  }
]

在我的服务中,我是这样理解的:

this.httpClient.get( environment.apiUrl + this.config.getSettings()['cleard']['api']['user']['Domain'], { headers: new HttpHeaders({ 'Authorization': 'BEARER ' + this.auth.getUserSession().access_token }), responseType: 'json'}).toPromise().then(
      (Domain: any) => {
        console.log(typeof (Domain));
        this.Domain = Domain;
        console.log('domains : ' + Domain + ' this.domainID : ' + this.Domain);
      });

我在 Web API 中的模型类是:

public class DomainBO
{
        public int Id { get; set; }
        public string DomainName { get; set; }

        public int DomainTypeId { get; set; }
        public string DomainTypeName { get; set; }
}

为什么我不能将它解析为我的角度对象?

谢谢女孩和男孩:)

标签: angularparsinghttpclient

解决方案


您的背景可能来自强类型语言:)

所以在 TS/JS 中,没有反序列化器。有一些解决方案,所以你可以反序列化,但我会避免它们,因为它是不必要的。

因此,当您这样做时,this.httpClient.get(url, (response: DomainBO) => {});不会实例化您的类。

您需要自己手动实例化对象:

this.httpClient.get(url, (response: any) => {
     this.domain = new Domain(response.id)
});

然而,这仍然不是一个理想的解决方案,因为response:any. 您可以做的是创建一个Interface

export interface Domain {
    id: string;
}

然后你可以像这样使用它:

this.httpClient.get(url, (response: Domain) => {
 this.domain = new Domain(response.id)
 console.log('domains : ' + Domain + ' this.domainID);
});

推荐阅读