2014-12-02 72 views
0

edit.html解決承諾值推遲對象>資源鏈

<div>timezone: {{userPreferencesCtrl.preference.response.format}}<div> 

UserPreferencesCtrl

this.preference = UserPreferencesFactory.userPreference; 

UserPreferencesFactory

基本上有兩種其餘-calls。拳頭 - 獲取所有的用戶偏好,並在其成功時調用另一個休息呼叫 - 獲得特定的用戶偏好。

var factory = this; 

factory.userPreference = $q.defer(); 
...  
UserPreferencesResource.all().$promise.then(   
    function(data) { 
     // some code 
     if (foundRightGuy) {    
      // get preference by ID 
      UserPreferencesResource.get({id: pref.preferenceID}).$promise.then(
      function(data) { 
       factory.userPreference.resolve(data); // resolving the promise 
      } 
     ); 
     } 
    } 
); 

return this;  }]); 

的問題是,在控制器端我看到了解決的承諾是這樣的:

{"promise":{"$$state":{"status":1,"value":{"response":{"preferenceID":2,"user_name":"name3", "format":"keyvalue"}}}}} 

這不會對edit.html渲染。

如何讓它在屏幕上顯示preference.response.format值?

UPDATE:(angularjs 1.3.x版)

如果不是$q.defer();我把UserPreferencesResource.get({id: 2})電話 - 那麼所有的渲染好。只是說所有變量都是好的(沒有拼寫錯誤或什麼的)。

+0

你在我的答案中嘗試了代碼嗎?被緩存的對象的屬性是沒有$的promise。 – cbass 2014-12-02 19:31:59

+0

剛剛嘗試過。更新了我的更新。 – ses 2014-12-02 19:36:25

+0

你仍然沒有解開承諾。 – cbass 2014-12-02 19:37:06

回答

1

當您致電UserPreferencesFactory.userPreference時,您得到的是已緩存的對象,它具有作爲屬性的承諾。所以你必須打開這個承諾。

控制器:

this.preference; 

UserPreferencesFactory 
    .userPreference 
    .promise 
    .then(function(data) { 
    this.preference = data; 
    }); 
0

更好的方式來在Ctr -> Factory -> Resource鏈連接數據是這樣的:

UserPreferencesCtrl

this.preference = UserPreferencesFactory.userPreference 

所以沒必要引用promise或做then。這是非常人工的做法。

然後在Factory無需做任何$q.defer$q.resolve要麼。但是,相反,這可能是如此簡單:

factory.userPreference = {} // default value 
UserPreferencesResource.all().then(function(data) { 
    //... may be more calls if we need it 
    angular.extend(factory.userPreference, data); // that part is important 
}) 

angular.extend - 將數據複製到退出源 - 到factory.userPreference。這使得Ctrl看到更改/更新。否則,做任務factory.userPreference = data不會讓改變爲Controller

這就是爲什麼之前我試圖resolve/reject承諾手動避免直接賦值是可見的 - 讓控制器和工廠之間的角度結合的作品。但angular.extend似乎更清潔的解決方案。

否則,樣板編碼的頂部,這樣做的事情(對我來說)的手工方式導致了與繁重的問題,當它評估了所有這些「開放的承諾」,如:var promise = UserPreferenceFactory.userPreference.promise; + some other unexpected issues.

所以,不要猶豫,使用angular.extend如果你發現自己寫了太多的承諾......並以這種方式更新狀態。這是我今天給自己的建議。