我正在从AngularJS转移到Angular 6,在JS中我使用了$resource
,当我得到的数据看起来像这样......
{
"SomeList": [{
"SomeID": "123456",
"SomeName": "Joe Shmoe",
"SomeCode": "987654",
"Address1": null,
"Address2": null,
"City": null,
"State": null,
"Zip": null,
"Phone1": null,
"Phone2": null,
"Email": null
},
{
"SomeID": "234567",
"SomeName": "Joe Bagodonuts",
"SomeCode": "456123",
"Address1": null,
"Address2": null,
"City": null,
"State": null,
"Zip": null,
"Phone1": null,
"Phone2": null,
"Email": null
},
etc...
]
}
它只是很好地流入变量,我可以使用数据。
在打字稿中我设置了......
一个模型
export class SomeList {
SomeID: string;
SomeName: string;
SomeCode: string;
Address1: string;
Address2: string;
City: string;
State: string;
Zip: string;
Phone1: string;
Phone2: string;
Email: string;
}
export class SimpleResponse < T > {
Data: T;
}
export class SimpleResponseLower < T > {
data: T;
}
在单例中设置为模型的变量
public static somies: SomeList[];
数据服务
getSomeList<SomeList>(year: number): Observable<SomeList[]>{
const url = `${Urls.Somies()}?cropYear=` + year;
var host = window.location;
var combineurl = host.href + 'api/RequestHandler?uri=' + url;
return this.http.get<SimpleResponse<SomeList[]>>(combineurl).pipe(map(r =>
r.Data));
***The call below is what returned the sample data above
//return this.http.get(combineurl).pipe(map(value =>{return value}));
}
}
和一个填写课程的数据服务的调用
this.dataService.getSomeList < SomeList > (2018)
.subscribe((data) => {
this._formValues.somies = data;
},
() => {
// put some code here and remove console.log
}); // end of error block);
}
我已经尝试了几乎所有我能想到的配置,并且数据返回“未定义”且没有错误,并且浏览器的“网络”选项卡中列出了链接。
非常感谢任何帮助或想法!
您的JSON应直接映射到您的模型。
您的数据应该是:
'{
"Data": [
{
"SomeID": "123456",
"SomeName": "Joe Shmoe",
"SomeCode": "987654",
"Address1": null,
"Address2": null,
"City": null,
"State": null,
"Zip": null,
"Phone1": null,
"Phone2": null,
"Email": null
}, etc...
]
}
或者你的简单回应应该期待SomeList
:
export class SimpleResponse<T> {
SomeList: T;
}
你应该在响应上映射到SomeList
属性而不是Data
。
return this.http.get<SimpleResponse<SomeList[]>>(combineurl).pipe(map(r
=> r.SomeList));
好的,我能够弄清楚这一点。我必须做的是......
更改从api返回的类型
string jsonString = client.DownloadString(fullUri);
JObject infoObj = JsonConvert.DeserializeObject<dynamic>(jsonString);
string data = infoObj.ToString();
return data;
至
string jsonString = client.DownloadString(fullUri);
JObject infoObj = JsonConvert.DeserializeObject<dynamic>(jsonString);
SimpleResponse<JObject> data = new
SimpleResponse<JObject>();
data.Data = infoObj;
return data;
在typeScript方面,我不得不将模型更改为
export class SimpleResponse<data> {
data: data;
}
export class SomeResponse{
SomeList: SomeList[];
Message: string;
}
并在我的数据服务而不是返回...
<SimpleResponse<SomeList[]>>
我回来
<SimpleResponse<SomeResponse>>
我不确定这是否是“TypeScript”这样做的方式,或者是否有更好的通用方式,所以我不必为每次调用API添加一个ResposeClass ......但它正在工作!