Angular 解析被拒绝,但页面仍在加载
Angular resolve is rejected, but page is still loading
这个 resolve 函数在其他任何地方都有效,我很困惑为什么当 promise 被拒绝时配置文件页面仍在执行。我们通过登录、从存储中删除令牌然后尝试导航到个人资料页面来产生此错误。它通过所有身份验证步骤,然后注销。它到达了重定向行,但随后它仍然加载了配置文件页面,并抛出错误,因为授权已被清除。
如果您能提供任何帮助,那就太好了。如果您需要更多信息,请告诉我。
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
}
}
/profile
路由总是解析,因为 auth
总是 return 已解析的承诺(或者更好地说:它不会 return 拒绝承诺并且不会抛出例外)。正确的代码是:
.when('/profile', {
templateUrl: '/templates/profile.html',
controller: 'ProfileController',
resolve: {
auth: function (SessionService) {
return SessionService.resolve()
}
}
}).
请注意,auth
处理程序 return 的承诺非常重要。如果省略 return
关键字,它会导致隐式 return undefined
。这没有意义,但仍被视为已解决的承诺。
这个 resolve 函数在其他任何地方都有效,我很困惑为什么当 promise 被拒绝时配置文件页面仍在执行。我们通过登录、从存储中删除令牌然后尝试导航到个人资料页面来产生此错误。它通过所有身份验证步骤,然后注销。它到达了重定向行,但随后它仍然加载了配置文件页面,并抛出错误,因为授权已被清除。
如果您能提供任何帮助,那就太好了。如果您需要更多信息,请告诉我。
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
}
}
/profile
路由总是解析,因为 auth
总是 return 已解析的承诺(或者更好地说:它不会 return 拒绝承诺并且不会抛出例外)。正确的代码是:
.when('/profile', {
templateUrl: '/templates/profile.html',
controller: 'ProfileController',
resolve: {
auth: function (SessionService) {
return SessionService.resolve()
}
}
}).
请注意,auth
处理程序 return 的承诺非常重要。如果省略 return
关键字,它会导致隐式 return undefined
。这没有意义,但仍被视为已解决的承诺。