【发布时间】:2019-10-28 20:21:28
【问题描述】:
由于我是 Angular 的新手,并且想使用正确的设计原则,因此我想将接口用于数据结构。
这是来自服务器的 JSON 响应:
{
"appGroup": "Brokerage",
"appName": "app-api",
"appType": "Mulesoft",
"config": "tmxpath,",
"dashboard": "dashboard",
"healthCheckURL": "api/ping",
"hostList": [
{
"hostID": "host1",
"port": 8080,
"domain": "sampletmxdomain"
},
{
"hostID": "host2",
"port": 443,
"domain": "tmxdomain2"
}
]
}
在此,如您所见,hostList 是一个对象数组。所以我无法定义和使用接口和对象。
这是我现在拥有的:
界面
export interface IAppOnboard {
appName: string;
appGroup: string;
appType: string;
config: string[];
dashboard: string;
healthCheckURL: string;
hostList: Ihost[];
}
export interface Ihost{
hostID: string;
port: number;
domain?: string;
}
接口对象
IHostsOb: Ihost[] = [{
hostID: '',
port: null,
domain: ''
}];
IAppOnboardOb : IAppOnboard ={
appName: '',
appGroup: '',
appType: '',
config: [],
dashboard: '',
healthCheckURL: '',
hostList: this.IHostsOb
};
我最终以上述方式定义了接口对象初始化,但不知何故它似乎不正确并导致问题。我可以在这里得到一些帮助吗?
在投反对票之前,请记住,我已经浏览了一些帖子,但找不到适合我的解决方案。
编辑
我产生了疑问,因为我遇到了一个错误:
this.onboardingService.getOnboardingDashboardData(this.dlArray).subscribe((res: any) => {
const selectedApp = res.applications.find(application => application.appName === app);
if(selectedApp){
let k;
this.IHostsOb = selectedApp.hostList;
this.IAppOnboardOb.config = selectedApp.hostList[0].config;
for(k in selectedApp.hostList){
this.addHostPort(selectedApp.hostList[k].hostID,selectedApp.hostList[k].port,selectedApp.hostList[k].hostID.domain) //This line Works Fine
this.IHostsOb[k].hostID = selectedApp.hostList[k].hostID;
this.IHostsOb[k].port = selectedApp.hostList[k].port;
this.IHostsOb[k].domain = selectedApp.hostList[k].domain;
this.IAppOnboardOb.hostList.push(selectedApp.hostList[k]);
}
}
}
上述函数为数组中的所有对象元素分配相同的值。
例如:IAppOnboardOb 的hostlist 变成这样:
"hostList": [
{
"hostID": "host1",
"port": 8080,
"domain": "sampletmxdomain"
},
{
"hostID": "host1",
"port": 8080,
"domain": "sampletmxdomain"
}]
注意 selectedApp 的结构相似 与定义的接口的结构。不一样。
【问题讨论】:
-
我最终以上述方式定义了接口对象初始化,但不知何故它似乎不正确并导致问题。我可以在这里得到一些帮助吗?你能更具体一点吗?
标签: angular typescript interface