简体   繁体   English

使用Angular ngResource的自定义URL

[英]Custom URL using Angular ngResource

I would like to know the best practice for connecting with my API as it works as following: 我想了解连接我的API的最佳做法,因为它的工作原理如下:

  • GET -> products/list/ latest -> return list of latest products GET->产品/列表/ 最新 ->返回最新产品列表
  • GET -> products/list/ popular -> return list of popular products GET->产品/列表/ 热门 ->返回热门产品列表
  • GET -> products/list/ trending -> return list of trending products GET->产品/列表/ 趋势 ->返回趋势产品列表

and then when I want a detail of the each product, it is just: 然后,当我想要每种产品的详细信息时,它只是:

GET -> products/:id GET->产品/:ID

I got the following code in my services.js: 我在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. 但是我真的不知道如何访问这些自定义URL。 Can I use the ngResource for that? 我可以使用ngResource吗?

Thanks! 谢谢!

Please see here https://docs.angularjs.org/api/ngResource/service/ $resource 请在这里查看https://docs.angularjs.org/api/ngResource/service/ $ resource

you can add custom action to ngResources 您可以将自定义操作添加到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="angular.js@1.4.x" 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM