我试图阻止用户进入某条路线,如果他没有付款方式。这是代码:
resolve: {
hasPayment: ['userService', 'paymentsService','$q', function( userService,paymentsService, $q ) {
if(userService.oAuth) {
paymentsService.getPayments().then(function(res) {
if(res.data.data.length) return $q.reject({hasPayment:true});
});
}
}]
}
$rootScope.$on('$stateChangeError', function(event, toState,toParams, fromState, fromParams, error) {
console.log(error);
});
但如果条件为真,它不会得到错误,为什么?
答案 0 :(得分:3)
您需要返回一个将被拒绝的承诺,使用$ q.reject您只需创建一个新的延迟并拒绝它,但“resolve”将不会等待此响应,因为它不知道它。
最好的办法是直接在paymentsService.getPayments()中拒绝承诺, 然后你的代码看起来像这样:
resolve: {
hasPayment: ['userService', 'paymentsService','$q', function( userService,paymentsService, $q ) {
return paymentsService.getPayments();
}]
}
如果由于某种原因你不能这样做,只需创建一个新的承诺并拒绝它,有些像这样:
resolve: {
hasPayment: ['userService', 'paymentsService','$q', function( userService,paymentsService, $q ) {
var deferred = $q.defer();
if(userService.oAuth) {
paymentsService.getPayments().then(function(res) {
if(res.data.data.length) {
deferred.reject({hasPayment:false});
} else {
deferred.resolve();
}
});
} else {
deferred.resolve();
}
return deferred.promise;
}]
}
答案 1 :(得分:0)
我想评论Asaf David的解决方案,但需要一个代码块来演示,所以发布作为答案(如果有更好的机制,请告诉我)
由于承诺的最终结果是返回的承诺链的结果,您可以简单地链接.then()
并从内部返回适当的值。如果不使用" deferred anti-pattern"那么Asaf的答案可以写得更简单。 (https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns):
resolve: {
hasPayment: ['userService', 'paymentsService','$q', function( userService,paymentsService, $q ) {
if(userService.oAuth) {
return paymentsService.getPayments().then(function(res) {
if (res.data.data.length)
return $q.reject({hasPayment: false}); // hasPayment is rejected.
// since you seem to be using hasPayment as a pass/fail you could even
// get by without returning anything here, but return true to be explicit.
return true;
}
}
}]
}