I have the following code, which was working fine until I deployed to a test server:
$scope.getUserList = function (userName) { $http({ method: "get", url: "GetUserList", params: { userName: userName } }). success(function (data) { $scope.users = data; }). error(function () { alert("Error getting users.");
The problem is that I deployed to a virtual directory, and the call below is attempting to hit GetUserList from the server root. This makes sense, and I know a number of ways to fix it.
What I would like to know is the right way to reference the service URL in a way that is portable and maintainable in Angular.
It is tempting to do too much work in the AngularJS controller. After all, the controller is where the view first has access to JavaScript via $scope functions. However, doing this will cause you to miss out on code sharing across the site and is not recommended by AngularJS documentation.
The $location in AngularJS basically uses a window. location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS.
We will be using the $location. absURL() method to get the complete URL of the current page.
path([path]);Return path of current URL when called without any parameter. Change path when called with parameter and return $location . Note: Path should always begin with forward slash (/), this method will add the forward slash if it is missing.
I'd suggest using an HTML base tag in the head, and coding all paths relative to this. In ASP.NET, for example, you can get a reference to the base of the application, which may or may not be the root path of the site, so using a base tag helps. Bonus: it works for every other asset too.
You can have a base path like this:
<base href="/application_root/" />
...and then links like "foo/bar.html" will actually be /application_root/foo/bar.html.
Another approach I like to use is to put named links in the header. I will often have an API root in one location and a directive template root somewhere else. In the head, I'll then add some tags like this:
<link id="linkApiRoot" href="/application_root/api/"/> <link id="linkTemplateRoot" href="/application_root/Content/Templates/"/>
... and then use $provide in the module to get the link href and expose it to services and directives like so:
angular.module("app.services", []) .config(["$provide", function ($provide) { $provide.value("apiRoot", $("#linkApiRoot").attr("href")); }]);
... and then inject it to a service like this:
angular.module("app.services").factory("myAdminSvc", ["apiRoot", function (apiRoot) { var apiAdminRoot = apiRoot + "admin/"; ...
Just my opinion though. Do the least complex thing for your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With