Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度-在返回的JSON数组中强制使用模型格式_Angular_Typescript_Angular2 Services - Fatal编程技术网

Angular 角度-在返回的JSON数组中强制使用模型格式

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

使用Angular时,我有以下模型:

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没有定义函数,并且由于强制转换,编译器无法捕获它