对返回promise的函数使用.success时,Undefined不是函数
Undefined is not a function when using .success on a function that returns a promise
我正试图通过编写登录函数来继续理解promise。Login函数是AuthService的一部分,它向我的服务器发送http请求并返回promise(如果验证了用户,则promise得到解决,如果未验证则拒绝)。
当调用我的控制器中的函数时,我尝试使用.success和.error,因为该函数返回了一个promise,但我得到了错误"Undefined is not a function"。
这是我的函数,它获取未定义的错误。
$scope.login = function(email, password) {
return AuthService.login(email, password).success(function(data) {
return console.log("login function returned", data);
}).error((function(data) {
return console.log("There was an error " + data);
}));
};
这是我的服务
.service('AuthService', function($window, $rootScope, $q, $http) {
return {
login: function(email, password) {
var deferred;
deferred = $q.defer();
$http.post('/dashboard/login', {
email: email,
password: password
}).error(function(error, status) {
console.log("Incorrect logi");
return deferred.reject(error);
}).success(function(data, status) {
$window.sessionStorage["userInfo"] = JSON.stringify(data);
return deferred.resolve(data);
});
return deferred.promise;
}
};
});
最让我困惑的是,经过研究,promise似乎没有成功或错误的方法,但$http是一个有这种方法的promise。同样,如果他们没有成功和错误,你怎么知道某件事是不是错误?最后,如果没有成功或错误的方法,那么拒绝和解决有什么意义?
最让我困惑的是,经过研究,promise似乎没有成功或错误的方法,但$http是一个有方法的promise
是的,的确如此。$http
返回对象是由于遗留原因也具有这些.success
和.error
方法的承诺。
如果他们没有成功和错误,你怎么知道某件事是不是错误?
将处理程序附加到promise的标准方法是使用.then()
方法,该方法也充当链接方法,并为处理程序的结果返回一个新的promise。
因此,代码看起来是这样的(也避免了延迟的反模式):
.service('AuthService', function($window, $rootScope, $q, $http) {
return {
login: function(email, password) {
return $http.post('/dashboard/login', {
email: email,
password: password
}).then(function(data, status) {
$window.sessionStorage["userInfo"] = JSON.stringify(data);
return data;
}, function(error, status) {
console.log("Incorrect login");
throw error;
});
}
};
});
$scope.login = function(email, password) {
return AuthService.login(email, password).then(function(data) {
return console.log("login function returned", data);
}, function(err) {
return console.log("There was an error " + err);
});
};
相关文章:
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- 为什么会出现错误,“UncaughtTypeError:undefined不是函数”
- mongoose.connect undefined不是一个函数
- Uncaught TypeError:undefined不是函数-ember js
- jQuery Mobile Undefined不是一个函数
- 未捕获的类型错误:undefined不是函数$
- 使用在函数外部声明的变量的 Javascript 返回值 + undefined
- 为什么Grunt Copy给了我一个'undefined不是函数'警告
- Bootstrap-“;未捕获的类型错误:undefined不是函数;
- Undefined不是函数ImpressPages DatePicker
- 尝试使用.ninnerHTMLlog打印数据,获取错误Uncaught TypeError:undefined不是函数
- 得到“;undefined不是函数“;错误
- Undefined不是Fullcalendar js上的函数
- 使用谷歌地图:一个返回undefined的自定义javascript函数
- jqGrid:undefined不是函数
- Jquery,Uncaught TypeError:undefined不是函数
- $http.post undefined 不是函数
- Ember cli Uncatch TypeError: undefined 不是函数
- Infragistics igGrid Uncatch TypeError: undefined 不是一个函数
- 如果构造函数在另一个函数中,则新创建的对象调用构造函数undefined