Search code examples
angularjsapiurlngresource

Custom URL using Angular ngResource


I would like to know the best practice for connecting with my API as it works as following:

  • GET -> products/list/latest -> return list of latest products
  • GET -> products/list/popular -> return list of popular products
  • GET -> products/list/trending -> return list of trending products

and then when I want a detail of the each product, it is just:

GET -> products/:id

I got the following code in my services.js:

.factory('ProductService', function ($resource) {
    return $resource('http://domainname.com/api/products/:product',{product: "@product"});
})

But I really don't know how to access these custom URLs. Can I use the ngResource for that?

Thanks!


Solution

  • Please see here https://docs.angularjs.org/api/ngResource/service/$resource

    you can add custom action to ngResources

    ie:

    var app = angular.module('app', ['ngResource']);
    
    
    app.factory('ProductService', function($resource) {
    
      var actions = {
    
        'latest': {
          method: 'GET',
          url: 'api/products/latest '
    
        },
    
        'popular': {
          method: 'GET',
          url: 'api/products/popular'
    
        },
    
        'trending': {
          method: 'GET',
          url: 'api/products/trending '
    
        }
    
    
      };
    
      var ProductService = $resource('/api/products/:productId', {ProductId: '@id'}, actions);
    
      return ProductService;
    
    });
    app.controller('MainCtrl', function($scope, ProductService) {
      $scope.name = 'World';
    
      ProductService.latest();
      ProductService.popular();
      ProductService.trending();
      ProductService.query();
      ProductService.get({id: 1});
    });
    <!DOCTYPE html>
    <html ng-app="app">
    
    <head>
      <meta charset="utf-8" />
      <title>AngularJS Plunker</title>
      <script>
        document.write('<base href="' + document.location + '" />');
      </script>
      <link rel="stylesheet" href="style.css" />
      <script data-require="[email protected]" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-resource.min.js"></script>
      <script src="app.js"></script>
    </head>
    
    <body ng-controller="MainCtrl">
      <p>Hello {{name}}!</p>
    </body>
    
    </html>