Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the base URL for a resource

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.

like image 936
Dylan Pierce Avatar asked Mar 17 '23 03:03

Dylan Pierce


1 Answers

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!');
});
like image 131
Dylan Pierce Avatar answered Mar 28 '23 01:03

Dylan Pierce