2015-02-05 105 views
3

我正在使用Angular在同一應用程序上使用RESTful API。我在http://sample-site.com/api/contacts更改資源的基本URL

這是偉大的,它的工作原理爲contacts資源$資源建立,但是我需要用的/api/contacts上的應用程序的不同頁面的基本CRUD交互。

例如,我需要在位於http://sample-site/friends/{friend-id}的Web應用程序的另一個頁面再次與聯繫人進行交互。但是,當我嘗試在該頁面上使用我的聯繫人資源時,資源的URL被附加到當前的 URL:

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

但我真正需要的是GET |該頁面上的該資源上的http://sample-site/api/contact

有沒有辦法配置一個資源來定義一個不同於當前頁面的基礎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。無論我如何定義$資源,只要將任何網址附加到基本網址即可。我需要更改URL的基礎。

回答

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