我使用 Auth0 进行登录,并且有以下代码:
$scope.login = function () {
$scope.loginFailed = false;
$scope.loading = true;
loaderService.show();
let credentials = {
email: $scope.email,
password: $scope.password
};
principal.signin(credentials)
.then(() => {
$state.go('main.index');
})
.catch(e => {
showError(e.error_description);
loaderService.hide();
});
};
原理
服务包含登录功能:
signin(credentials) {
return new Promise((resolve, reject) => {
this.auth.signin({
connection: 'Username-Password-Authentication',
email: credentials.email,
sso: false,
password: credentials.password,
authParams: {
scope: 'openid name email'
}
}, this.onLoginSuccess.bind(this, resolve, reject), this.onLoginFailed.bind(this, reject));
});
}
因此,正如您所看到的,我创建了 Promise 并将解析/拒绝传递给 Auth0 回调。 回调非常简单:
onLoginSuccess(resolve, reject, profile, token) {
let userData = this.collectData(profile);
... store token
return this.syncCurrent(userData) //request to server
.then(() => {
return resolve();
})
.catch(() => {
this.signOut();
return reject();
});
}
onLoginFailed(reject, error) {
return reject(error.details);
}
那么,让我们回到第一个片段。有以下代码:
principal.signin(credentials)
.then(() => {
$state.go('main.index');
})
.catch(e => {
showError(e.error_description);
loaderService.hide();
});
当我使用正确的电子邮件/密码重定向工作正常,我看到主页。但是,当我使用错误的电子邮件/密码时,我看到 catch
block 被执行,我看到调试器中的值发生了更改,但我没有看到错误 block ,并且加载图像也没有消失。这在html中不是问题,因为我现在正在重构代码,上面的所有代码都在一个文件中,并且我没有使用promise,并且一切正常。我尝试在principal.signin(credentials)函数之前执行showError方法,只是为了测试,我看到错误并且加载图像被隐藏。所以,我认为问题出在 Promise 和 catch block 上,但我不知道在哪里。
showError
如下:
function showError(errorText) {
$scope.loading = false;
$scope.loginFailed = true;
$scope.loginErrorMessage = errorText;
}
最佳答案
此问题的原因是使用非 Angular Promise。 Angular Promise,即 $q
服务,负责在解析后调用摘要周期。摘要周期是 Angular 1 中变更检测的实现,即通知观察者并允许执行操作。
使用$q
解决了这个问题。
代码的 then
部分可能有效,因为它调用了 $state.go()
,而后者又调用了摘要循环。 catch
部分没有,因此更改永远没有机会触发观察者。
关于javascript - 使用 Promise.catch 时,Angular、Binding 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41932647/