【问题标题】:Angular resolve is rejected, but page is still loading角度解析被拒绝,但页面仍在加载
【发布时间】:2016-04-25 09:39:26
【问题描述】:

这个解析函数在其他任何地方都有效,我很困惑为什么当承诺被拒绝时配置文件页面仍在执行。我们通过登录、从存储中删除令牌然后尝试导航到配置文件页面来产生此错误。它会完成所有身份验证步骤,然后注销。它到达了重定向行,但它仍然加载配置文件页面,由于身份验证已被清除而引发错误。

您能提供的任何帮助都会很棒。如果您需要更多信息,请告诉我。

app.config('$routeProvider')

.when('/profile', {
    templateUrl: '/templates/profile.html',
    controller: 'ProfileController',
    resolve: {
        auth: function (SessionService) {
            SessionService.resolve()
        }
    }
}).
otherwise({
    redirectTo: '/login'
})

function resolve () {
    if (self.isAuthenticated()) {
        return $q.when({auth: true})
    } else {
        $q.reject({auth: false})
            self.logout() // first we go here
        }   
    }
}

function logout () {
    var auth = self.storage()
    if (...) {
       ...
    } else {
        self.clearUserAuthentication() // then here
        $location.path('/login') // it redirects here, but still initializes the profile controller
    }
}

【问题讨论】:

    标签: javascript angularjs resolve


    【解决方案1】:

    /profile 路由总是解析,因为auth 总是返回已解决的承诺(或者更好地说:它不返回被拒绝的承诺并且不抛出异常)。正确的代码是:

    .when('/profile', {
        templateUrl: '/templates/profile.html',
        controller: 'ProfileController',
        resolve: {
            auth: function (SessionService) {
                return SessionService.resolve()
            }
        }
    }).
    

    注意,auth 处理程序返回承诺非常重要。如果您省略 return 关键字,则会导致隐式 return undefined。这是没有意义的,但仍被视为已解决的承诺。

    【讨论】:

    • 解析失败时是否还需要返回 $q.reject ? @dfsq
    • SessionService.resolve() 需要返回将被解决或拒绝的承诺。或throw 错误(相当于拒绝)。我可以看到在resolve方法中你需要添加return $q.reject({auth: false})
    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2018-07-19
    • 2012-06-09
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多