在AngularJS中有一个在$http之后运行的finally
In AngularJS is there such a thing as a finally that runs after $http?
我的代码如下:
$scope.login = function (userName, password, rememberMe) {
authentication.authenticating = true;
var config = {
method: 'POST',
url: '/api/Account/Login',
data: { 'userName': userName, 'password': password, 'rememberMe': rememberMe }
};
$http(config)
.success(function (data) {
authentication.authenticating = false;
authentication.isAuthenticated = true;
$scope.template = $scope.templates[1];
$scope.userName = userName;
})
.error(function (data) {
$scope.loginError = "Invalid username/password combination";
authentication.authenticating = false;
});
};
有没有办法移动authentication.authentication=false;转换成某个总是在错误或成功后执行的代码块?
是的,由于$http
返回promise,因此可以调用.finally(callback)
方法,如$q文档中所述https://docs.angularjs.org/api/ng/service/$q
所以你可以像这个一样在你的情况下使用它
$scope.login = function (userName, password, rememberMe) {
authentication.authenticating = true;
var config = {...};
$http(config)
.success(function (data) {
authentication.isAuthenticated = true;
$scope.template = $scope.templates[1];
$scope.userName = userName;
})
.error(function (data) {
$scope.loginError = "Invalid username/password combination";
})
.finally(function() {
authentication.authenticating = false;
});
};
尝试promise($q)
使用$q.delated获取对象,然后可以在成功或错误中使用resolve或reject http方法
对不起,我的回答很简短。
您可以将代码移动到另一个方法中,就像这样,但您仍然需要从成功或失败函数中手动调用它:
var setAuthenticating = function(){
authentication.authenticating = false;
}
$scope.login = function (userName, password, rememberMe) {
authentication.authenticating = true;
var config = {
method: 'POST',
url: '/api/Account/Login',
data: { 'userName': userName, 'password': password, 'rememberMe': rememberMe }
};
$http(config)
.success(function (data) {
setAuthenticating();
authentication.isAuthenticated = true;
$scope.template = $scope.templates[1];
$scope.userName = userName;
})
.error(function (data) {
$scope.loginError = "Invalid username/password combination";
setAuthenticating();
});
};
相关文章:
- 如何使用phaser使html5游戏在移动设备浏览器上运行
- 使用压缩的JavaScript文件(不是运行时压缩)
- Javascript运行php文件,然后下载文件
- chrome扩展:尽管运行了at:documentidle,js脚本还是过早启动
- 我已经创建了一个jquery转盘,并使用if条件来运行和停止转盘
- Angularjs代码未在匿名函数中运行
- jquery设置为使用参数运行
- 如何根据时间运行不同的脚本
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- 将文本框链接到由按钮运行的javascript公式
- 为什么不是't运行此Javascript的Chrome
- ng应用程序使脚本无限运行
- 如何在运行时在angular 2中加载外部js脚本
- 与运行长作业(javascript,node.js)的第三方API同步的最佳实践
- JavaScript错误:Microsoft JScript运行时错误:应为对象
- 在终端中运行 JavaScript 时(使用 rhino),如何使用 print() 函数在一行中打印
- 如何使用JS/nightwatchjs并行运行多个测试
- 茉莉花宝石-耙茉莉花:ci dons't运行测试
- 我的HTML按钮没有在Javascript中运行
- 在AngularJS中有一个在$http之后运行的finally