您好我正在使用以下代码调用我的API
$http.get('/api/controller/method?param=value').
then(function (response) {
if (response.status == 200) {
console.log(response.data);
}
});
它在我的本地计算机(MongoDB documentation)中正常运行。
但是当我在应用程序名称 app 的服务器中部署它时,它无法调用API(http://localhost/api/controller/method?param=value)。
显然,它不会,因为URL不同。 那么在c#中调用API的正确方法是什么,以便它可以在任何服务器上运行。
我的尝试:
1. URL.Action :在这种情况下不起作用
2.我不想使用 @ HTML.hidden
3.使用或不使用斜杠(/)
答案 0 :(得分:1)
我通常使用像这样的factory
来解决这个问题 -
首先在.cshtml页面中加载所需的所有角度js。 然后像这样为baseURL创建一个工厂 -
function(angular){
var module = angular.module('NameOfMyModule'); //gt the module
module.factory('BaseUrl', function(){
return '@Url.Action("Action", "Controller")';
});
}(window.angular);
然后在控制器中注入BaseURL
-
....
module.controller('SomeController', [...., 'BaseUrl', function(...., BaseUrl){
$scope.baseUrl = BaseUrl;
}]);
....`
最后将其添加到网址
中$http.get($scope.baseUrl + /...../).then(....);
答案 1 :(得分:0)
我不确定我是否正确地检查了你的问题,但我使用的是角度常数来设置服务器网址
angular.constant("CONSTS", {
"DEV_URL": "http://localhost:12345",
"LIVE_URL": "http://server-ip/app"
})
然后在$ http call
中$http.get(CONSTS.DEV_URL + '/api/controller/method?param=value').
then(function (response) {
if (response.status == 200) {
console.log(response.data);
}
});
我确信有一种方法可以自动化(gulp,grunt),但我还没到达那里。 部署应用程序时,我只需手动更改常量。 如果我找到了自己的方法,我会更新答案。
希望这有点帮助...
答案 2 :(得分:0)
我不知道您的构建过程等,但通常您可以将应用程序路径存储在Angular中的某个常量值中,并在将API作为前缀调用时使用它。
如果你有某种自动构建,很容易准备更改值的部署包(使用Gulp / Grunt / TeamCity / Octopus,无论你喜欢什么)。
答案 3 :(得分:0)
//controller
app.controller("sampleController", function($scope, commonService) {
//post
$scope.postData = function() {
var command = {}
commonService.postSample(command);
}
//get
commonService.getSample().then(function(data) {
$scope.permissionList = data;
});
});
//service
app.service('commonService', function($http, $q) {
this.postSample = function(command) {
var deferred = $q.defer();
$http({
method: 'POST',
data: command,
url: '/Attendance/CreatePersonDailyLeave'
})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
this.getSample = function(id) {
var deferred = $q.defer();
$http({
method: 'GET',
async: true,
url: '/Attendance/GetRoles?id=' + id
})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
});