我已经创建了angularJs工厂服务来处理REST调用。服务工作正常。我有一些情况需要将值设置为$ scope.variable并在资源服务外部访问它们。但我得到了未定义。我将它们包裹在angularJs $q
里面,但似乎我犯了一些错误。请帮助我解决这个问题。
AngularJs Factory
myApp.factory('MyService',function($resource) {
return{
GetMYData:$resource(my rest service URL, {});
}
});
在控制器中
$scope.myMap={};
$scope.promises=[];
$scope.myData = MyService.GetMYData.query();
$scope.myData.$promise.then(function (result) {
result.forEach(function(e, i) {
//Do something
var deferred = $q.defer();
$scope.myMap[e.key]=e; //Put elements into map and i tried to access map from outside service by giving key
deferred.resolve(result);
$scope.promises.push(deferred.promise);
$scope.myMap[$location.search()['dataID']] //This display the actual value
})
...
}
如果URL中存在URL参数,我会执行以下操作。
if($location.search()['dataID']){
$q.all($scope.promises).then(
function(data) {
console.log($scope.myMap[$location.search()['dataID']]) // throws undefined
},function(response) {
//Handle if promises are rejected
})
}
请告诉我如何从服务外部访问angularJs资源服务设置的地图值。
答案 0 :(得分:0)
我将尝试做的是:
myApp.factory('MyService',function($resource) {
var _resource = $resource(my rest service URL, {},{
query:{method:"GET",IsArray:true}
})
return{
GetMYData:function(){
return _resource.query();
}
}
});
然后:
$scope.myMap={};
$scope.promises=[];
MyService.GetMYData.$promise.then(function (result) {
result.forEach(function(e, i) {
//Do something
$scope.myMap[e.key]=e; //Put elements into map and i tried to access map from outside service by giving key
$scope.myMap[$location.search()['dataID']] //This display the actual value
})
...
}
然后只访问您的
if($location.search()['dataID']){
console.log($scope.myMap[$location.search()['dataID']]) );
}