Wednesday, July 16, 2014

Angular.js: using relative paths

One of the issues I had with Angular.js (but also with other JavaScript frameworks) is that URL’s you create on the client are relative to the server root address. This is fine as long as your application is hosted on the server root(e.g. www.myservername.com), but the moment you start using virtual directories(e.g. www.myservername.com/virtualdirectoryname ), you’re into trouble.

Let’s have a look for example to the following Angular service:

The problem is that when you host this service in a virtual directory, the HTTP call will be send to http://www.myservername.com/api/applications and not to www.myservername.com/virtualdirectoryname/api/applications as you would expect.

There a multiple ways to solve this issue.  I did it by rendering the rootUrl inside my ASP.NET Razor view. This url is generated by the server and embedded in the page:

Inside my Angular app, I added some code that read this value from the html and register it as a constant value:

This allows me to inject this value anywhere I need it, let’s have a look at the refactored service:

7 comments:

ROR Development company said...

Very nice!! There is so much information on this blog keep posting good information like this so that I can come back every day for some new info...

Sai Santosh said...

We never miss a single post from this useful website related to js and angularjs. After attending online Angularjs training, this site worked as a supplementary knowledge to our technical knowledge to the knowledge I gained from my instructors.

Raju Kumar said...

Thank you for sharing this knowledge in a blogpost.Really simple and even more effective and this worked great, very useful tips
Angularjs Training In Hyderabad

Pavel said...

Thank you SO MUCH!!!

Elton Serra said...

I made it with angular value:

(function() {
angular.module('myModule').value('server', getURL());

function getURL() {
var _baseURL = $('#baseURL').attr('href');
return {
baseURL: _baseURL
};
}
})();

Devi.Angularjs said...

It's really great and easy to understand if you are new to AngularJS. Thanks!

Angularjs Training | Angularjs Online Training


angular2 Training in Chennai | angular2 Training in Chennai

Angular 2 Training in Chennai | Angularjs Training | Angularjs Training | Angular 2 Training in Chennai | Angular 2 Online Training

onlinetrainings expert said...
This comment has been removed by the author.