Angular 角度-在返回的JSON数组中强制使用模型格式
使用Angular时,我有以下模型:Angular 角度-在返回的JSON数组中强制使用模型格式,angular,typescript,angular2-services,Angular,Typescript,Angular2 Services,使用Angular时,我有以下模型: export interface MyModel { id: number; content: string; } 在服务中,我请求具有MyModel属性的JSON数据。大概是这样的: function getMyModel() { return this.http .post('http://www.somewhere.com/getOneModel') .map(result => <My
export interface MyModel {
id: number;
content: string;
}
在服务中,我请求具有MyModel属性的JSON数据。大概是这样的:
function getMyModel() {
return this.http
.post('http://www.somewhere.com/getOneModel')
.map(result => <MyModel> result.json())
.catch(this.handleError);
}
{ id: 1, content: "Stuff" }
{[
{ id: 1, content: "Stuff" },
{ id: 2, content: "More stuff" }
]}
在getMyModel()
中,您将看到,当我map()
查看结果时,我通过执行以下操作确保JSON符合MyModel:result.JSON()
到目前为止,一切正常
现在,我想返回一组模型,并确认它们都符合MyModel
function getLotsOfModels() {
return this.http
.post('http://www.somewhere.com/getLotsOfModels')
.map(result => result.json())
.catch(this.handleError);
}
返回的JSON如下所示:
function getMyModel() {
return this.http
.post('http://www.somewhere.com/getOneModel')
.map(result => <MyModel> result.json())
.catch(this.handleError);
}
{ id: 1, content: "Stuff" }
{[
{ id: 1, content: "Stuff" },
{ id: 2, content: "More stuff" }
]}
在这种情况下,
map()
无法确认JSON数组元素是否与MyModel一致,因为结果是数组。如何检查结果是否正确 您应该在那里使用数组
/列表
,将其指示为一个集合
.map(result => Array<MyModel> result.json())
.map(结果=>Array result.json())
您可以将它们强制转换为MyModel[]
function getLotsOfModels() {
return this.http
.post('http://www.somewhere.com/getLotsOfModels')
.map(result => <MyModel[]> result.json())
.catch(this.handleError);
}
这将在运行时抛出一个错误,因为底层JSON没有定义函数,并且由于强制转换,编译器无法捕获它