Question

Just trying to get a very simple REST get call to work using angularjs $resource service. The API is never called. Here is the code:

angular.module('app.services', [])
.service('tourRepository', function ($resource) {
    this.get = function (id) {
        alert('tourRepositoryCalled for id ' + id + '!');  // this is called
        var tour = $resource('/api/tour/:tourid', { tourId: '@id' });
        return tour.get({ tourId: id }, function () {
            alert('tour api called.');  // THIS NEVER IS
        });
    }

If I use a browser and go to /api/tour/3, it works. What am I doing wrong here? I thought $resource calls could be much easier, for example like below, but I am following angularjs documentation.

Ideally:

$scope.tour = $resource.get('/api/tour/' + id);   // why wouldn't this work?

All that I want to do is call a simple REST service and assign the results to my $scope.tour object. Since I'm in a service though (my 'repository') I don't have access to the $scope. What's the best way to go about this? When I change the code to below the API is getting hit.

        var tour = $resource('/api/tour/:tourid');
        var theTour = tour.get({ tourid: id });
        alert(theTour.id);
Was it helpful?

Solution

For simple models you can use $http instead of $resource

$http.get('/api/tour/' + id).success(function (tour) {
  $scope.tour = tour;

});

$resource is a service for creating javascript classes (ActiveRecord style).

var Tour = $resource(...) // capital T
var tour1 = Tour.get()

Although slightly confusing, your code should work. does the ajax request take place? and does it return a valid response?

OTHER TIPS

Once the get request is completed the returned object is filled with the data got from the response, there's no callback in the $resource's get method.

$resource is useful when you attach the object which is returned by the call to a scope instance. In this case when the object is resolved and the digest loop is called the view is being automatically updated.

If you need a callback you can use:

$http.get('/api/tour/' + id)
.then(function (tour) {
    $scope.tour = tour;
});

By using your services you can:

function MyCtrl($scope, tourRepository) {
  $scope.tour = tourRepository.get(ID_OF_THE_TOUR);
}

You have to include ngResource module in your app('app.services') dependencies. The spelling of tourid in the url must be tourId

angular.module('app.services', ['ngResource'])
.service('tourRepository', function ($resource) {
    this.get = function (id) {
        alert('tourRepositoryCalled for id ' + id + '!');
        var tour = $resource('/api/tour/:tourId', { tourId: '@id' });
        return tour.get({ tourId: id }, function () {
            alert('tour api called.'); 
        });
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top