使用相对路径在AngularJS服务呼叫 [英] Using a Relative Path for a Service Call in AngularJS

查看:176
本文介绍了使用相对路径在AngularJS服务呼叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,直到我部署到测试服务器,这是工作的罚款:

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.");

的问题是,我部署到虚拟目录,下面的呼叫正在尝试从服务器根击中GetUserList。这是有道理的,我知道了一些方法来解决这个问题。

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.

我想知道的是的右键的方式来引用服务URL的方式,是便携式和维护的角度。

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.

推荐答案

我建议在头部使用HTML基标记和编码相对于这一切的路径。在ASP.NET中,例如,你可以得到应用,这可能是也可能不是网站的根路径的基础上的引用,所以使用基本标记帮助。奖金:它适用于所有其他资产过

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/" />

...然后链接像富/一个bar.html实际上将/application_root/foo/bar.html。

...and then links like "foo/bar.html" will actually be /application_root/foo/bar.html.

我喜欢使用的另一种方法是把名为链接在标题中。我经常会在一个位置的API的根和指令模板根别处。在头部,我会再加入一些标签是这样的:

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/"/>

...然后使用$提供模块中获取链接href和暴露于服务和指令,像这样:

... 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.

这篇关于使用相对路径在AngularJS服务呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆