Angularjs数据是从在范围异步服务空 [英] Angularjs data is null from async service in scope
问题描述
在预先感谢阅读我的文章。
thanks in advance for read my post.
我有一个服务,是这样的:
I have a service, like this:
angular.module('myApp.services')
.factory('myService', function($http, $q) {
var myService = {
getId: function() {
var defer = $q.defer();
$http.get('http://xxxxxxxxxxxxxxxxxx/id/')
.success( function(data) {
defer.resolve(data);
})
.error( function(data) {
defer.reject(data);
});
return defer.promise;
},
begin : function(jsonBegin) {
var defer = $q.defer();
$http.post('http://xxxxxxxxxxxxxxxxxxxxxxx/begin/?format=json', jsonBegin)
.success( function(data) {
defer.resolve(data);
})
.error( function(data) {
defer.reject(data);
});
return defer.promise;
}
};
return myService;
});
一个父控制器(正常工作):
A parent controller (works fine):
angular.module('myApp.controllers')
.controller('controllerA', function($scope, myService) {
myService.getId()
.then(function(data) {
$scope.bID = data.bID;
});
});
和子控制器:
angular.module('myApp.controllers')
.controller('controllerB', function($scope) {
console.log($scope.$parent.bID);
});
有关申办的console.log值是不确定的,做ü知道为什么吗?我设置了家长控制槽为myService服务,变量。我想我的问题是由于异步调用,但我不知道。
The console.log value for bID is undefined, do u know why? I am setting that variable in the parent controller trough myService service. I guess my problem is due to the asynchronous call but I'm not sure.
感谢。
推荐答案
您可以做这样的事情:
angular.module('myApp.controllers')
.controller('controllerA', function($scope, myService) {
$scope.bID = myService.getId()
.then(function(data) {
return data.bID;
});
});
angular.module('myApp.controllers')
.controller('controllerB', function($scope) {
$scope.$parent.bID.then(function(bID) { console.log(bID); });
});
子范围将等待家长来解决竞标。而当家长出价已解决,将立即在子作用域承诺返回值。这是一个有点杂乱,虽然期待。
The child scope will wait for the parent to resolve bID. And when parent bID is already resolved, it will immediately return the value in the child scope promise. It's a little messy looking though.
另一种方法是让控制器加载前为myService要求的决心。检查了这一点:
The alternative is to have the myService request resolve before the controller loads. Check this out:
的http://www.$c$clord.net/2015/06/02/angularjs-pitfalls-using-ui-routers-resolve/
然后就可以设置父范围解析值并访问其作为子作用域正常的财产。
Then you can set the parent scope to the resolved value and access it as a normal property in the child scope.
这篇关于Angularjs数据是从在范围异步服务空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!