Using ngResource in an AngularJS SPA

2019-09-08 02:18发布

问题:

I am using ngResource in a factory to fetch data from a REST API URL, and then do some basic processing on the retrieved data. This works fine (verified using console.log()). I injected the dependencies properly in my root module and in the main controller, and set a $scope variable equal to this retrieved data.

In HTML, I put {{variableName}} inside the desired tag. However, it doesn't get populated.

What am I missing? Do I need to add $watch or something else in order for this to work?

PS -

var dataResource = $resource("http://<URL>"); $scope.trialData = dataResource.get();

This trialData populates values from the same URL just fine when I add this directly to the controller.

回答1:

Resources use asynchronous request. You have to wait for their promise to be resolved like this :

dataResource.get().$promise.then(function(object){
   $scope.trialData = object;// or maybe object.data
});