[英]How can I update my view model from chained promises?
I'm quite new to promises. 我对诺言很陌生。 I have a hard time trying to update an object used in my view from 2 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;
};
EDIT : firstPromise
is exposed in another service, and used by other services : 编辑:
firstPromise
在另一个服务中公开,并由其他服务使用:
$resource(apiUrl).get(user).$promise.then(function(bookData){
angular.extend(self.bookings, bookData);
});
In my controller : 在我的控制器中:
function TestController(Test) {
'ngInject';
var $ctrl = this;
$ctrl.testData = {};
Test.getTestData();
$ctrl.testData = Test.data;
};
Instead self.data
will not be displayed until the resolution of the second promise. 相反,直到第二个承诺解决后,
self.data
才会显示。 How can I make my object available for my controller directly when the first promise is resolved ? 解决第一个承诺后,如何使我的对象直接可用于我的控制器?
It the firstPromise
is a $q Service promise, the view should be updating. 如果
firstPromise
是$ q服务承诺,则视图应该正在更新。 Since the view is not updating, use $q.when() to convert the unknown promise to a $q Service promise: 由于视图未更新,请使用$ 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 Service promises are integrated with the AngularJS framework and its digest cycle. $ q服务承诺已与AngularJS框架及其摘要周期集成在一起。
$q.when(value)
$ q.when(值)
Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
将可能是值或(第三方)然后可承诺的对象包装为$ q承诺。 This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
当您处理可能是或可能不是承诺的对象时,或者如果承诺来自无法信任的来源时,这很有用。
-- AngularJS $q Service API Reference - $q.when
-AngularJS $ q服务API参考-$ q.when
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.