我想知道连接我的API的最佳做法,因为它的工作原理如下:
然后当我想要了解每个产品的细节时,它只是:
GET - >产品/:ID
我在services.js中获得了以下代码:
.factory('ProductService', function ($resource) {
return $resource('http://domainname.com/api/products/:product',{product: "@product"});
})
但我真的不知道如何访问这些自定义网址。我可以使用ngResource吗?
谢谢!
答案 0 :(得分:3)
请参阅此处https://docs.angularjs.org/api/ngResource/service/ $ resource
您可以向ngResources添加自定义操作
即:
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>
&#13;