在 AngularJS 中为服务调用使用相对路径 [英] Using a Relative Path for a Service Call in AngularJS
问题描述
我有以下代码,在我部署到测试服务器之前它运行良好:
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.
我想知道的是正确以一种在 Angular 中可移植和可维护的方式引用服务 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/" />
...然后像foo/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/"/>
... 然后在模块中使用 $provide 获取链接 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屋!