在使用 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);
}
返回的 JSON 是这样的:
{ id: 1, content: "Stuff" }
在 getMyModel()
当我map()
时你会看到的结果我通过这样做确保 JSON 符合 MyModel:<MyModel> result.json()
.
到目前为止一切正常。
现在我想返回一个模型数组并确认它们全部符合 MyModel。
function getLotsOfModels() {
return this.http
.post('http://www.somewhere.com/getLotsOfModels')
.map(result => result.json())
.catch(this.handleError);
}
返回的 JSON 是这样的:
{[
{ id: 1, content: "Stuff" },
{ id: 2, content: "More stuff" }
]}
在本例中map()
无法确认 JSON 数组元素与 MyModel 一致,因为结果是一个数组。如何检查结果是否正确?
最佳答案
您可以将它们转换为MyModel[]
。
function getLotsOfModels() {
return this.http
.post('http://www.somewhere.com/getLotsOfModels')
.map(result => <MyModel[]> result.json())
.catch(this.handleError);
}
Typescript 不会进行任何结构检查,因此强制转换只能在运行时失败。如果您在 MyModel
上有任何方法。 Json 不会有它们,当你想调用一个方法时,你会遇到问题。
例如,在获得模型后:
myModel.myMethod();
这将在运行时抛出错误,因为底层 JSON 没有定义函数,并且编译器由于强制转换而无法捕获它。
关于Angular - 在返回的 JSON 数组中强制执行模型格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36584212/