Get Data on conditions by $resource angualrjs

无人久伴 提交于 2019-12-31 07:12:30

问题


I am using $resource service for my crud operations now i want to get data on a condition like get appointments whose starting date is today. I am fetching all data by

vm.appointments = AppointmentsService.query();

and my service code is

    (function () {
  'use strict';

  angular
    .module('appointments')
    .factory('AppointmentsService', AppointmentsService);

  AppointmentsService.$inject = ['$resource'];

  function AppointmentsService($resource) {
    return $resource('api/appointments/:appointmentId', {
      appointmentId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
})();

Now can i give condition in this code blockAppointmentsService.query({condition}); or change my service in node rest API. If yes, then what will be my AppointmentsService.query call


回答1:


For your different url path, you can create new method like below or you can pass startDate as a query string

Controller :

For Path Param

 vm.appointments = AppointmentsService.searchByDate({date:'03/30/2016'});

For Query Param

vm.appointments = AppointmentsService.searchByDate({StartDate:'03/01/2016',EndDate:'03/30/2016'});

Service:

 function AppointmentsService($resource) {
    return $resource('api/appointments/:appointmentId', {
      appointmentId: '@_id'
    }, {
      update: {
        method: 'PUT'
      },
      // For Path Param
      searchByDate :{
        method : 'GET',
        url : 'your url/:date'
      },
     // For Query Param
      searchByDate :{
        method : 'GET',
        url : 'your url/:startDate/:endDate' ,
        params : { startDate : '@StartDate', endDate : '@EndDate' } 
      }
    });
  }



回答2:


Update your service code...

 (function () {
     'use strict';

  angular
    .module('appointments')
    .factory('AppointmentsService', AppointmentsService);

  AppointmentsService.$inject = ['$resource'];

  function AppointmentsService($resource) {
    var service = {
        get: $resource('api/appointments/:appointmentId',{
           appointmentId: '@_id'
        },{
           method:'GET'
        }),
        update: $resource('api/appointments/:appointmentId',{
           appointmentId: '@_id'
        },{
           method:'PUT'
        }),
        query:$resource('api/appointments',{
           method:'GET',
           isArray:true
        })
        queryByStartDate:$resource('api/appointments/:startDate',{
           startDate: '@_startDate'
        },{
           method:'GET',
           isArray:true
        })
    }
    return service;
   }
})();

And call queryByStartDate inside controller

var startDate = new Date(); //you can use $filter to format date
$scope.appointments = AppointmentsService.queryByStartDate({startDate:startDate});


来源:https://stackoverflow.com/questions/36310771/get-data-on-conditions-by-resource-angualrjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!