2016-04-12 28 views
2

一個模型格式在使用角我有以下模式:角 - 執行在返回的JSON陣列

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同意由於結果是一個數組。我如何檢查結果是否正確?

回答

4

您可以將它們投射到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,不具備的功能定義和編譯器不能抓住它因爲演員。

+1

完美。謝謝。 – ebakunin

0

您應該在那裏使用Array/List,以表明它是一個集合。

.map(result => Array<MyModel> result.json())