角度6:接收对象和解析对象时出现问题



我从webAPI 收到

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

我用字符串得到这个对象:

[
{
"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; }
}

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

谢谢大家:(

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

因此,在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);
});

最新更新