更改资源的基本URL

时间:2015-02-05 13:26:41

标签: angularjs angular-resource

我正在使用Angular在同一个应用程序上使用RESTful API。我在contacts

处为http://sample-site.com/api/contacts资源设置了资源

这很棒且有效,但我需要在应用程序的不同页面上与/api/contacts的基本CRUD进行交互。

例如,我需要在http://sample-site/friends/{friend-id}托管的网络应用上的其他网页上再次与联系人互动。但是,当我尝试在该页面上使用我的联系人资源时,资源的网址会附加到当前网址:

GET | 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的基础。

1 个答案:

答案 0 :(得分:6)

我明白了!

.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!');
});
相关问题