2013-07-29 44 views
0

我有一個問題解決我的諾言,奇怪這是在我的標記:角JS只承諾解決的標記,而不是模擬

{{details.customer_email}} 

它解決正確,並顯示'$ http`請求返回的電子郵件地址。

但是,試圖訪問此:

$scope.user = { 
    ... 
    emailAddress : $scope.details.customer_email, 
    ... 
}; 

null

下面是相關的功能塊:

$scope.session = { 
    is_authenticated: false, 
    customer_email: null 
}; 

var detailsDeferred = $q.defer(); 

$scope.details = detailsDeferred.promise; 

$scope.authed = function() { 

    $http({ 
     url: 'http://api.foo/auth', 
     withCredentials: true, 
     method: "GET", 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded' 
     } 
    }).success(function (data, status, xhr) { 

      $scope.session = { 
       is_authenticated: data.is_authenticated, 
       customer_email: data.customer_email 
      }; 

      detailsDeferred.resolve($scope.session); 


     }) 
     ... 

    return $scope.session; 

}; 

$scope.authed(); 

$scope.user = { 
    ... 
    emailAddress: $scope.session.customer_email 
     ... 
    }; 

回答

1

它的工作在你的標記是因爲角度的模板引擎「承諾感知」,這是非常方便的。

doc引用:

$ Q承諾通過在角模板引擎,這意味着在模板中,你可以把連接到一個範圍的承諾,如果他們得到的價值確認。

在你的JavaScript代碼,但是,你必須自己來處理這一切:

$scope.user = { 
    ... 
    emailAddress : null, 
    ... 
}; 

$scope.details.then(function(details) { 
    $scope.user.emailAddress = details.customer_email; 
}); 
+0

謝謝!值得注意的是我必須重新定義'then()'中的'$ scope.user'對象的*全部*才能使其工作。不知道這是爲什麼...... – couzzi

+0

你也許想在你的'$ scope.user'中使用defer/promise,我的2美分。 –

+0

其實,這是行不通的 - 只有刷新頁面後,這些值纔會更新。 – couzzi