我已经用这种方式定义了登录服务:
.factory('Auth', ['$http', '$location', 'sharedProperties', 'CONSTANTS', function ($http, $location, sharedProperties, CONSTANTS) {
return {
login: function (username, password) {
$http.get(CONSTANTS.BASE_URL + '/auth', {
id: username,
mdp: password
}).success(function (data) {
sharedProperties.setApiToken(data);
$location.path('routes');
}
).error(function (data) {
return 'Some error message';
}
)
}
}
}])
在我的控制器中,如果出现问题,我该如何收到错误消息?
我试过这种方式:
$scope.login = function () {
Auth.login(
{
id: "testcorp",
mdp: "companyPassword"
}, function (data) {
console.log(data);
}
);
}
但是没有调用console.log(data)指令。
谢谢,
马修。
答案 0 :(得分:1)
我建议您创建承诺工厂并向控制器返回承诺。像:
.factory('Auth', ['$http', '$location', 'sharedProperties', 'CONSTANTS', function ($http, $location, sharedProperties, CONSTANTS) {
return {
login: function (username, password) {
var data = $http.get(CONSTANTS.BASE_URL + '/auth', {
id: username,
mdp: password
});
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
}])
之后,来自控制器:
Auth.login("testcorp", "companyPassword")
.then(function (result) {
$scope.data = result;
}, function (result) {
alert("Error: No data returned");
});
作为参考
承诺代表未来值,通常是异步操作的未来结果,并允许我们定义一旦发生这种情况会发生什么值变为可用,或发生错误时。