Search code examples
angularjsapicross-domainangular-resource

How and where to define a default domain for my angular resource?


Where can and should I define a default url for my angular resource so I don't have to provide an absolute url for every api endpoint that I have?

(The api that I am using is on the same domain but with a a subdomain: http://api.myapp.app/api/v1)

I am quite new to angular and I am trying really hard to get a thorough understanding so I would be ever so thankful if someone could also explain to me the "why" behind the answer.


Solution

  • If your using a build system like grunt and your deployment servers will change I would look into grunt-ng-constant

    Otherwise you can simply define a constant in your app config like:

    angular
        .module('app', [])
        .constant("ENV", {
            "ApiEndpoint": "somedomain.com"
        });
    

    Then you can pass that around like:

    angular.module('app').controller('SomeCtrl', function(ENV) {
        // ENV.ApiEndpoint
    });
    

    Not a true default per se, but at least you won't manually need to type out your base domain in every resource, you'll only need to reference ENV.ApiEndpoint