我正在使用 Angular 在同一应用程序上使用 RESTful API。我在 http://sample-site.com/api/contacts
contacts
资源设置了 $resource
这很棒并且有效,但是我需要在应用程序的不同页面上与 /api/contacts
的基本 CRUD 进行交互。
例如,我需要在 http://sample-site/friends/{friend-id}
托管的网络应用程序的另一个页面上再次与联系人交互。但是,当我尝试在该页面上使用我的联系人资源时,该资源的 URL 会附加到当前 URL:
获取| http://sample-site/friends/1/api/contact
但我真正需要的是 GET |该页面上该资源的 http://sample-site/api/contact
。
有没有办法配置资源来定义与当前页面相关的不同基本 URL?
这是我尝试更改资源内的基本 URL:
.factory('ContactRest', ['$resource', '$location', function($resource, $location) {
var host = $location.host()
return $resource('https://:url/:action', {}, {
// Normal CRUD actions
query: {
url : host,
action : 'api/contact',
method : 'GET',
isArray : true,
}
}]);
这使得https://sample-site/friends/1/sample-site/api/contact
。不管我如何定义 $resource,只是不断将任何 URL 附加到基本 URL 上。我需要更改 URL 的基础。
最佳答案
我明白了!
.factory('ContactRest', ['$resource', '$location', function($resource, $location) {
var host = $location.host()
return $resource('http://' + host + ':action', {}, {
// Normal CRUD actions
query: {
method : 'GET',
isArray : true,
}
}]);
/**
* In controller
*/
ContactRest.query({ action: 'api/contact' }, function(contact) {
console.log('Got it, take that Havascript!');
});
关于angularjs - 更改资源的基本 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28345165/