Phi*_*ler 66 javascript angularjs
我有以下代码,在我部署到测试服务器之前工作正常:
$scope.getUserList = function (userName) {
$http({
method: "get",
url: "GetUserList",
params: { userName: userName }
}).
success(function (data) {
$scope.users = data;
}).
error(function () {
alert("Error getting users.");
Run Code Online (Sandbox Code Playgroud)
问题是我部署到虚拟目录,下面的调用试图从服务器根命中GetUserList.这是有道理的,我知道了很多方法来解决它.
我想知道的是以Angular中可移植和可维护的方式引用服务URL 的正确方法.
Bar*_*all 105
我建议在头部使用HTML基本标记,并编码与此相关的所有路径.例如,在ASP.NET中,您可以获得对应用程序基础的引用,该引用可能是也可能不是站点的根路径,因此使用基本标记会有所帮助.额外奖励:它也适用于所有其他资产.
你可以有这样的基本路径:
<base href="/application_root/" />
Run Code Online (Sandbox Code Playgroud)
...然后像"foo/bar.html"这样的链接实际上是/application_root/foo/bar.html.
我喜欢使用的另一种方法是将标题链接放在标题中.我经常在一个位置有一个API根,在其他地方有一个指令模板根.在头部,我会添加一些像这样的标签:
<link id="linkApiRoot" href="/application_root/api/"/>
<link id="linkTemplateRoot" href="/application_root/Content/Templates/"/>
Run Code Online (Sandbox Code Playgroud)
...然后在模块中使用$ provide来获取链接href并将其公开给服务和指令,如下所示:
angular.module("app.services", [])
.config(["$provide", function ($provide) {
$provide.value("apiRoot", $("#linkApiRoot").attr("href"));
}]);
Run Code Online (Sandbox Code Playgroud)
...然后将它注入这样的服务:
angular.module("app.services").factory("myAdminSvc", ["apiRoot", function (apiRoot) {
var apiAdminRoot = apiRoot + "admin/";
...
Run Code Online (Sandbox Code Playgroud)
只是我的意见.为您的应用程序做最简单的事情.
jva*_*emo 28
我建议定义一个包含全局配置的模块,然后可以在应用程序中传递:
// Module specific configuration
angular.module('app.config')
.value('app.config', {
basePath: '/' // Set your base path here
});
Run Code Online (Sandbox Code Playgroud)
然后,由于AngularJS依赖注入,您可以从应用程序中的任何位置访问它:
// Make sure your config is included in your module
angular.module('app', ['app.config']);
// Access your config e.g. in a controller
angular.module('app')
.controller('TestCtrl', ['$scope','app.config', function($scope, config){
// Use config base path to assemble url
$scope.url = config.basePath + 'GetUserList';
...
}]);
Run Code Online (Sandbox Code Playgroud)
每当基本路径发生变化时(例如,当您更改为其他服务器或主机时),您只需在全局配置中更改它就可以完成.
End*_*ess 13
我无法使用<base>标签,因为我的应用程序是在另一个原始动态弹出窗口中创建的.我正在考虑此线程中的其他选项使用类似basePath变量的东西并在每个$http, ng-src, templateUrl等中使用它
但这有点开销,构建了一个拦截器,可以在xhr生成之前更改每个URL
var app = angular.module("myApp", []);
app.config(["$httpProvider", function($httpProvider) {
$httpProvider.interceptors.push('middleware');
}]);
app.factory('middleware', function() {
return {
request: function(config) {
// need more controlling when there is more than 1 domain involved
config.url = "//example.com/api/" + config.url
return config;
}
};
});
app.controller("Ctrl", ["$http", function($http) {
$http.get("books"); // actually requestUrl = http://example.com/api/books
}])
Run Code Online (Sandbox Code Playgroud)
和html一样
<div ng-include src="'view'">
<!-- actually src = http://example.com/api/view -->
</div>
Run Code Online (Sandbox Code Playgroud)
但我建议改为使用<base>标签,除非你使用window.popup()