簡體   English   中英

Angular,使用Promise.catch時綁定不起作用

[英]Angular, Binding doesn't work when use Promise.catch

我使用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();
            });
    };

principle服務包含登錄功能:

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塊已執行,我看到調試器中的值已更改,但是我沒有看到錯誤塊,並且未分解加載圖像。 在html中,這不是問題,因為我現在正在重構代碼,並且上面的所有代碼都在一個文件中,並且我沒有使用promises,而且一切正常。 我試圖在principal.signin(credentials)函數之前執行showError方法,僅用於測試,但我發現錯誤並隱藏了加載圖像。 因此,我認為問題出在promise和catch擋,但我不知道在哪里。

PS。 showError如下:

function showError(errorText) {
        $scope.loading = false;
        $scope.loginFailed = true;
        $scope.loginErrorMessage = errorText;
    }

造成此問題的原因是使用非角度承諾。 Angular Promise,即$q服務,在解決摘要循環后負責調用摘要循環。 摘要周期是Angular 1中變更檢測的實現,即通知觀察者並使動作發生的內容。

使用$q可解決此問題。

代碼的then部分可能起作用,因為它調用了$state.go() ,而后者又調用了摘要循環。 catch部分沒有,因此更改永遠沒有機會解雇觀察員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM