0

I am learning Angularjs and in my first application I am replacing the $http with $resource and getting error. The below was my earlier service and the current service:

angular.module('myApp')
  .service('fetchData', function ($http, $rootScope, myService) {
// AngularJS will instantiate a singleton by calling "new" on this function
  this.fetchNames=function() {
      return $http.get(myService.getDomainUrl() + '/names.json');
  }

});

Below is my new code with $resource

angular.module('myApp')
  .service('fetchData', function ($resource, $rootScope, myService) {
// AngularJS will instantiate a singleton by calling "new" on this function
return $resource(myService.getDomainUrl() + '/names.json', {
          query:{
              method: 'GET',
              cache: true
          }
      });
});

I am getting the below error: fetchData.fetchNames(...).success is not a function

When I try to handle the success callback when calling this function. Please tell me where I am going wrong and what is the correct way to handle the $resource in Angularjs.

2 Answers 2

1

Look docs: https://docs.angularjs.org/api/ngResource/service/$resource correct way is

var t = $resource(...);
t.query(successCallback, errorCallback)

Also notice that:

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

Sign up to request clarification or add additional context in comments.

Comments

0

$resource is a wrapper.

Declare it as

var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

And you available actions(methods to call) will be:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

I assume (without code how you use) that you don't invoke correct method. Ex.

var resource = $resource(....);

and use it like

resource.query({params}, function(){/*your success callback*/})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.