Change the base URL for a resource

こ雲淡風輕ζ 提交于 2019-12-22 11:14:24

问题


I'm using Angular to consume a RESTful API on the same application. I have a $resource setup for the contacts resource at http://sample-site.com/api/contacts

This is great and it works, however I need to interact with the basic CRUD of /api/contacts on different pages of the application.

For example, I need to interact with contacts again at another page on web app hosted at http://sample-site/friends/{friend-id}. However when I try to use my contact resource on that page, the url to the resource is appended to the current URL:

GET | http://sample-site/friends/1/api/contact

but what I really need is to GET | http://sample-site/api/contact on that resource on that page.

Is there a way to configure a resource to define a different base URL other than in relation to the current page?

This is my attempt to change the base URL inside the resource:

 .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,
    }
 }]);

Which makes https://sample-site/friends/1/sample-site/api/contact. Regardless of how I define the $resource, just keeps appending any URL's to the base URL. I need to change the very base of the URL.


回答1:


I got it!

.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!');
});


来源:https://stackoverflow.com/questions/28345165/change-the-base-url-for-a-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!