2014-10-02 29 views
3

默認情況下,當RESTAdapter向服務器發送一個請求,POST數據,它發出的模型typeKey作爲哈希的根:Ember-Data:我的自定義`serializeIntoHash`返回一個空的散列?

typeKey: { data } 

,但我的服務器需要一個「無根」的哈希:

{ data } 

我發現這是覆蓋的方法,但我正在做的事情不僅導致根被刪除,而且散列本身也是空的......即使我的console.log顯示record正在序列化到哈希。

import ApplicationSerializer from './application'; 

export default ApplicationSerializer.extend({ 

    serializeIntoHash: function(hash, type, record, options) { 

     console.log(' hash going in: ' + JSON.stringify(hash)); // hash is {} going in 

     hash = this.serialize(record, options); 

     console.log('hash going out: ' + JSON.stringify(hash)); // hash is { full of data } going out 

     return hash; // after this, for some reason the request goes out as an empty hash {} 
    } 

}); 

我是不是正確地返回修改後的散列?我也試過這些變化:

return (hash, type, record, options) 

return this._super(hash); 

return this._super(hash, type, record, options); 

沒有我回似乎工作。我不知道我做錯了什麼?

我注意到在API Docs for the method,沒有return使用,但如果我排除,我得到完全相同的問題,所以我不知道我是否甚至需要返回或沒有?

回答

3

serializeIntoHash方法是時髦,主叫方不指望你返回一個散列(如備註),它希望您修改在發送的哈希值。

這意味着,如果你只是設置散列,你將不再使用將被髮送的散列。您將需要設置屬性/從該實例中刪除屬性。

在這裏,他們合併的結果,以實現我在說什麼:https://github.com/emberjs/data/blob/v1.0.0-beta.10/packages/ember-data/lib/serializers/json_serializer.js#L500

+1

好的,這是有道理的。所以,如果我理解你,我需要單獨獲取'serialize(record,options)'的結果,並以某種方式循環並將結果中的屬性添加到散列中的鍵中? – Grapho 2014-10-02 16:14:42

+0

或...實際上將hash和serialize()的結果合併,就像在共享的鏈接中一樣? ...聽起來更容易 – Grapho 2014-10-02 16:24:41

0

我的猜測是在你的serializeIntoHash

import ApplicationSerializer from './application'; 

export default ApplicationSerializer.extend({ 

    serializeIntoHash: function(hash, type, record, options) { 

     console.log(' hash going in: ' + JSON.stringify(hash)); 

     hash = this.serialize(record, options); // <---- THIS LINE 

     console.log('hash going out: ' + JSON.stringify(hash)); 

     return hash; 
    } 

}); 

這有事情做與JavaScript關閉。 hash參數的值不會更改,而是javascript創建了hash的副本併爲其重新分配了新值。當功能完成時,參數hash保持不變,並且hash變量將被丟棄,因爲Ember rest.js source code不期望返回值。

你可以做的是

serializeIntoHash: function(hash, type, record, options) { 
    this._super(...arguments); // ES6 Syntax 

    // extract variable outside 
    Object.keys(hash.someInnerVariable).forEach(key => { 
     hash[key] = hash.someInnerVariable[key]; 
    }); 
    delete hash.someInnerVariable1 
    delete hash.someInnerVariable2 
} 

你的想法,改變散列變量本身,而不是重新分配它的價值。

讓我知道你是否還有其他問題。

相關問題