这是我的控制器,它正在调用登录服务
mod.controller("loginCtrl",function($scope,loginService,$http)
{
$scope.Userlogin = function()
{
var User = {
userid :$scope.uname,
pass:$scope.pass
};
var res = UserloginService(User);
console.log(res);
alert("login_succ");
}
});
这是登录服务代码,它接受用户变量并检查用户名&密码
mod.service("loginService",function($http,$q) {
UserloginService = function(User) {
var deffered = $q.defer();
$http({
method:'POST',
url:'http://localhost:8080/WebApplication4_1/login.htm',
data:User
}).then(function(data) {
deffered.resolve(data);
}).error(function(status) {
deffered.reject({
status:status
});
});
return deffered.promise;
// var response = $http({
//
// method:"post",
// url:"http://localhost:8080/WebApplication4_1/login.htm",
// data:JSON.stringify(User),
// dataType:"json"
// });
// return "Name";
}
});
我使用spring创建了一个rest api,在传递json时返回json中的用户名和密码,如下所示
控制台显示角度的此错误
答案 0 :(得分:1)
您需要为应用程序启用CORS以获得指导,请参阅此链接 https://htet101.wordpress.com/2014/01/22/cors-with-angularjs-and-spring-rest/
答案 1 :(得分:1)
我更喜欢使用Factory来做你想做的事情,这将是这样的:
MyApp.factory('MyService', ["$http", function($http) {
var urlBase = "http://localhost:3000";
return {
getRecent: function(numberOfItems) {
return $http.get(urlBase+"/things/recent?limit="+numberOfItems);
},
getSomethingElse: function(url) {
return $http.get(urlBase+"/other/things")
},
search: function (searchTerms) {
return $http.get(urlBase+"/search?q="+searchTerms);
}
}
}]);
然后在您的控制器中,您可以导入MyService
,然后以这种方式使用它:
MyService.getRecent(10).then(function(res) {
$scope.things = res.data;
});
这是处理它的好方法,因为您将.then
放在控制器中,并且如果您愿意,您可以在加载状态期间控制UI的状态,像这样:
// initialize the loading var, set to false
$scope.loading = false;
// create a reuseable update function, and inside use a promise for the ajax call,
// which is running inside the `Factory`
$scope.updateList = function() {
$scope.loading = true;
MyService.getRecent(10).then(function(res) {
$scope.loading = false;
$scope.things = res.data;
});
};
$scope.updateList();
答案 2 :(得分:1)
控制台中的错误显示代码存在两个问题:
Access-Control-Allow-Origin
标头启用CORS到您的rest api。 Unhandled rejection
错误,因为您使用“.error()”方法处理错误的方式已弃用。
根据{{3}}和Angular js github repo中的this,弃用了'Promise.error()'方法。
因此,您需要更改处理错误的方式,如下所示:
$http().then(successCallback, errorCallback);
function successCallback (res) {
return res;
}
function errorCallback (err) {
return err;
}
您的代码中可以避免的另一件事是您已经定义了一个新的承诺并使用$q
方法解决它,这不是必需的。默认情况下,$http
本身会返回promise
,您无需在其中再次定义它以将其用作Promise。您可以直接使用$http.then()
。