I have basically created a cache in my Angular
service. If the REST
call has already been made, the an array is returned, else it makes the REST
call to get the needed info. Here is my service:
define(function(require) {
var module = require('portal/js/services/app.services');
return module.factory('providerService', function($resource) {
return {
requestingProviders: [],
getRequestingProviders: function() {
var that = this;
if(this.requestingProviders.length === 0) {
this.getResource().search({
role: 'REQUESTING_PROVIDER'
}, function(data) {
that.requestingProviders = data.providers;
return that.requestingProviders;
});
} else {
return that.requestingProviders;
}
},
getResource: function() {
return $resource('/api/v1/providers/:providerId', {providerId:'@id'}, {
search: {
method: 'GET',
headers: {
'RemoteUser': 'jhornsby',
'Content-Type': 'application/json'
},
params: {
limit: 2000,
organizationId : '0001194'
}
}
});
}
};
};
Here is an example of me accessing the service from a controller:
define(function(require) {
var module = require('portal/js/controllers/app.controller');
module.controller('AddPatientCtrl', function($scope, providerService) {
$scope.providers = providerService.getRequestingProviders();
};
return module;
});
When the REST
call returns, it does not update my scope.providers
variable in my controller
. When I try to access it a 2nd time, then it works fine by accessing the array instead of calling out to the REST
service. WHy won't my scope
update in my controller
during the REST
call?
The prpblem is that you are calling an async get method
You'll have to assign the $scope in a callback function from the service (or in this case the factory) to make sure that it will take the desired value.
As you have said, in the first time $scope is assined to something that has not been yet resolved but in subsequent calls that parameter is resolved so $scope will get the proper value.
I hope it helped.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments