hkr*_*ss2 16 resources http angularjs angular-resource
我使用$ resource作为我的RESTful api,并且喜欢参数化的URL模板 'api/clients/:clientId'
这适用于CRUD操作.然而,我的一些api只是报告或只读端点,而不需要完整的RESTful处理.我觉得为那些人使用$ resource并使用$ http的自定义数据服务是有点过分.
唯一的缺点是我丢失了参数化的URL模板.我很乐意定义一个网址,'api/clients/:clientId/orders/:orderId'然后通过{ clientId: 1, orderId: 1 }.我意识到我可以动态构建url,但希望$ http支持参数化模板,我还没有找到它.
祝一切顺利
更新7/5
我在搜索中遗漏的这个词是'Interpolate'.当我搜索'angular $ http'中的url interpolation时,会出现更多信息.简短回答看起来是'不'$ http不支持url插值.然而,有一些相当简单的方法来实现这一点.
1.使用$ interpolate:
这里的文档$interpolate
var exp = $interpolate('/api/clients/{{clientId}}/jobs/{{jobId}}', false, null, true);
var url = exp({ clientId: 1, jobId: 1 });
Run Code Online (Sandbox Code Playgroud)
2.编写自己的url插值函数
Ben Nadel在这里有一个关于这个确切主题的精彩帖子.
3.从角度资源中窃取功能
查看angular-resource.js中 Route.prototype上的setUrlParams .这很简单.
(function () {
'use strict';
var serviceId = 'dataservice.jobsReports';
angular.module('app').factory(serviceId, ['$http', '$interpolate', function ($http, $interpolate) {
var _urlBase = 'http://localhost:59380/api';
var _endPoints = {
getJobsByClient: {
url: 'Clients/{{clientId}}/Jobs',
useUrlInterpolation: true,
interpolateFunc: null
}
};
// Create the interpolate functions when service is instantiated
angular.forEach(_endPoints, function (value, key) {
if (value.useUrlInterpolation) {
value.interpolateFunc = $interpolate(_urlBase + '/' + value.url, false, null, true);
}
});
return {
getJobsByClient: function (clientId) {
var url = _endPoints.getJobsByClient.interpolateFunc({ clientId: clientId });
return $http.get(url);
}
};
}]);
})();
Run Code Online (Sandbox Code Playgroud)
为了防止在已回答时“未回答”......
1.使用$插值:
此处的文档$interpolate
var exp = $interpolate('/api/clients/{{clientId}}/jobs/{{jobId}}', false, null, true);
var url = exp({ clientId: 1, jobId: 1 });
Run Code Online (Sandbox Code Playgroud)
2. 编写自己的url插值函数
Ben Nadel在这里发表了一篇关于这个主题的精彩文章。
3. 直接从角度资源中窃取功能
查看angular-resource.js中 Route.prototype 上的 setUrlParams 。这相当简单。
(function () {
'use strict';
var serviceId = 'dataservice.jobsReports';
angular.module('app').factory(serviceId, ['$http', '$interpolate', function ($http, $interpolate) {
var _urlBase = 'http://localhost:59380/api';
var _endPoints = {
getJobsByClient: {
url: 'Clients/{{clientId}}/Jobs',
useUrlInterpolation: true,
interpolateFunc: null
}
};
// Create the interpolate functions when service is instantiated
angular.forEach(_endPoints, function (value, key) {
if (value.useUrlInterpolation) {
value.interpolateFunc = $interpolate(_urlBase + '/' + value.url, false, null, true);
}
});
return {
getJobsByClient: function (clientId) {
var url = _endPoints.getJobsByClient.interpolateFunc({ clientId: clientId });
return $http.get(url);
}
};
}]);
})();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3739 次 |
| 最近记录: |