给定以下示例,I可以在工厂中返回承诺以在控制器中使用:
厂:
angular
.module('security.authorisation')
.factory('AuthService', [
'$http',
AuthService
]);
function AuthService($http, Endpoints, toastr) {
var authService = {};
// Login function.
authService.login = function (user, success, error) {
var login_url = Endpoints.getUrl("login");
$http.post(login_url)
.success(function (data) {
}).then(function (temp) {
console.log("suc");
}, function (err) {
console.log("err");
});
};
return authService;
}
登录控制器:
(function () {
'use strict';
angular
.module('login')
.controller('LoginController', [
'$scope',
'AuthService',
LoginController
]);
function LoginController($scope, AuthService) {
$scope.submit = function submit() {
$scope.app = AuthService.initModel;
AuthService.login($scope.app)
.then(function (greeting) {
alert('Success: ' + greeting);
}, function (reason) {
alert('Failed: ' + reason);
});
}
}
})();
我得到错误:
TypeError:无法读取未定义的属性“ then”
最佳答案
看来你忘了兑现诺言
authService.login = function (user, success, error) {
var login_url = Endpoints.getUrl("login");
return $http.post(login_url)
.success(function (data) {
}).then(function (temp) {
console.log("suc");
}, function (err) {
console.log("err");
});
//toaster.pop('success', "title", "text");
};