[英]How can I update my view model from chained promises?
我對諾言很陌生。 我很難嘗試從2個鏈接的諾言中更新視圖中使用的對象:
function Test($resource, FC, UserDetailsService) {
'ngInject';
var self = this;
self.data = {
};
function getTestData() {
firstPromise.then(function(response) {
//I want self.data to be displayed in my view
angular.extend(self.data, response);
//Now my view should display my object
resource().get(user)
.$promise.then(function(responsePts){
//And THEN update/refresh my view here
angular.extend(self.data, responsePts);
});
});
};
self.getTestData = getTestData;
};
編輯: firstPromise
在另一個服務中公開,並由其他服務使用:
$resource(apiUrl).get(user).$promise.then(function(bookData){
angular.extend(self.bookings, bookData);
});
在我的控制器中:
function TestController(Test) {
'ngInject';
var $ctrl = this;
$ctrl.testData = {};
Test.getTestData();
$ctrl.testData = Test.data;
};
相反,直到第二個承諾解決后, self.data
才會顯示。 解決第一個承諾后,如何使我的對象直接可用於我的控制器?
如果firstPromise
是$ q服務承諾,則視圖應該正在更新。 由於視圖未更新,請使用$ q.when()將未知的諾言轉換為$ q服務諾言:
function getTestData() {
//firstPromise.then(function(response) {
$q.when(firstPromise).then(function(response) {
//I want self.data to be displayed in my view
angular.extend(self.data, response);
//Now my view should display my object
//return to chain
return resource().get(user).$promise;
}).then(function(responsePts){
//And THEN update/refresh my view here
angular.extend(self.data, responsePts);
});
};
$ q服務承諾已與AngularJS框架及其摘要周期集成在一起。
$ q.when(值)
將可能是值或(第三方)然后可承諾的對象包裝為$ q承諾。 當您處理可能是或可能不是承諾的對象時,或者如果承諾來自無法信任的來源時,這很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.