2016-09-22 46 views
0

(恩伯2,如果它的事項)如何處理部分API數據的列表燼

我試圖表現出餘燼頁面上的搜索結果列表。我使用的api基本上只返回一個特定記錄類型的id和名稱列表(我們稱之爲foo)。不幸的是,我還需要爲每個項目獲取縮略圖,並且搜索結果路線不提供它。搜索結果模型由多個屬性的列表組成,每個屬性對於不同的模型簡單地是DS.hasMany

foos: DS.hasMany('foo', { 
    async: true 
    }), 
    bars: DS.hasMany('bar', { 
    async: true 
    }), 

的數據從服務器返回的是這樣的:

{ 
    "actions": [{ 
     ... irrelevant 
    }], 
    "data": { 
     "foos": [{ 
      "id": "test", 
      "name": "test" 
     }], 
     "meta": { 
      "total": 1 
     } 
    } 
} 

Foo的模型有很多屬性,包括namethumbnailURI

當我嘗試用{{foo.image}}我模板,屬性是未定義的;我本來預計該商店將獲取foo/test的模型,因爲它缺少圖片屬性,但它沒有。我該怎麼做才能告訴Ember - 嘿,服務器上的物品列表並沒有得到你需要的所有屬性;通過/api/foo/test,/api/foo/test2等問服務器的每個項目的數據。

回答

2

ember-data是不適合用分區加載模型。最好的方法是將你的模型分成兩部分。一個normal模型和一個detail模型。

然後你可以在你的適配器/序列化程序中解決這個問題。 通常其並不清楚適配器/對你使用,但是讓我們假設你有模型foofoo-detail

name: DS.attr('string'), 
detail: DS.belongsTo('foo-detail'), 
bars: DS.hasMany('bar'), 

富細節

image: DS.attr('string'), 

然後你的序列化器foo將不得不返回像這樣的東西:

{ 
    data: [{ 
     id: 'test', 
     type: 'foo', 
     attributes: { 
      name: 'first foo' 
     }, 
     relationships: { 
      "foo-detail": { 
       links: { 
        related: '/foo/test' 
       } 
      } 
     } 
    },{...}] 
} 

當您訪問{{fooInstance.detail.image}}時,這將強制請求/foo/test。接下來你必須確保foo-detail的序列化程序將返回這個結果:

{ 
    data: { 
     id: 'test', 
     type: 'foo-detail', 
     attributes: { 
      image: '/testimage.jpg' 
     } 
    } 
} 
+0

心靈只是在你的最後一句話上詳述一下嗎?我是新來的,仍然靜謐。我知道這些是什麼,但我不能立即確定你認爲的一般步驟是什麼。 – AlexMA

+0

@AlexMA我編輯了答案。 – Lux

+0

謝謝,這應該對我和其他人有幫助。 – AlexMA

相關問題