Reputation: 85
I am using angular v1.6.1 and ui-router v1.0.6 onBefore TransitionHook.
I am attempting to validate that the user has an active subscription set to true. This value is set on a user object. When they log in and attempt to hit any routes, I want to check to make sure they have the active subscription, if not reroute to the billing module so they can update their payment method. Even if they are in the app and attempt to click another route, I want them to be rerouted to the billing until that case is satisfied.
What happens is the onBefore hook just iterates or gets called multiple times (x20).
I must be missing something or not understanding. I have onStart hook that works fine.
//app.ts Run
$trace.enable("TRANSITION");
$transitions.onBefore({ to: "private.**" }, (trans) => {
//trans.$to().data.authorization = true
//authService.isLoggedIn() method = true
//$sessionStorage.profile.hasActiveSubscription = false
if (trans.$to().data.authorization && authService.isLoggedIn() && !$sessionStorage.profile.hasActiveSubscription) {
return trans.router.stateService.target("private.location.billing");
}
return true;
});
$transitions.onStart({}, trans => {
if (trans.$to().data && trans.$to().data.authorization && !authService.isLoggedIn()) {
return trans.router.stateService.target("public.login");
}
return true;
});
//route
.state("private.location.billing",
{
url: "/billing",
views: {
"tabContent": {
component: "billing",
data: { pageTitle: "Location Billing" }
}
},
ncyBreadcrumb: {
label: "Location Billing"
},
data: {
authorization: true
}
})
Upvotes: 4
Views: 1204
Reputation: 8216
When you redirect a transition in UI-Router, it aborts the original transition. It then starts a new transition to the state you targeted. Your hook is processed a second time when the new transition runs.
One option is to whitelist the "private.location.billing"
state in your hook. This would cause the hook to run for any private.**
states, except for private.location.billing
.
$transitions.onBefore({ to: "private.**" }, (trans) => {
const to = trans.to();
if (to.name !== "private.location.billing" && to.data.authorization && authService.isLoggedIn() && !$sessionStorage.profile.hasActiveSubscription) {
return trans.router.stateService.target("private.location.billing");
}
return true;
});
Upvotes: 2