Bhavani
Bhavani

Reputation: 41

How do I call $resource service from controller in angularJs

This is get service function where I am calling the API

    .factory('Report', function($resource, API_URL) {
       return $resource(API_URL  + 
       'security/:userId/1498780800000/listOfDeliveries', {

      userId : '@userId',
      expected : '@expected',
      arg1 : '@arg1'
    }, {
      update: {
        method: 'PUT'
      }
    });
  })

In the app.js I have this below controller

    .controller('ReportsController', function($scope, $rootScope, 
     ProfileData, $state, $timeout, Report) {


})

Upvotes: 0

Views: 268

Answers (1)

Fetrarij
Fetrarij

Reputation: 7326

First of all, you need to check how angular factory & service work.

Your factory return a $resource, so read the doc about $resource

A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:

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

So, you can use theses methods: Report.get(), Report.save(), Report.query(), Report.remove(), Report.delete()

In addition there are custom method you defined: Report.update()

And you can pass userId as params so:

Report.get({userId: 1234}); will call a GET request to: API_URL+'security/1234/1498780800000/listOfDeliveries

(expected and args1 are not in url so I dont think you need them)

What's returning Report.get() ?

Class actions return empty instance (with additional properties below). Instance actions return promise of the action

So Report.get(...) is returning a promise, you will get data by:

Report.get(...).then(function(data) {
  $scope.requestData = data;
});

Upvotes: 1

Related Questions