angular / router

The Angular 1 Component Router
MIT License
665 stars 135 forks source link

Infinite loop #414

Open iliesalex89 opened 8 years ago

iliesalex89 commented 8 years ago

Hello,

I have a small problem with component router for angular 1. When I'm trying to redirect/ navigate to another component from $routerOnActivate lifecyle hook, I'm getting into an infinite loop of redirects from current component to desired component. In the best case scenario is not infinite, but it will redirect between those two paths multiple times. What I am trying to do is that if something goes wrong, I want to go my home page. So basically I'm trying to do something like: this.$routerOnActivate = () => { this.$router.navigate(["abcd"] }

If i'm wrapping the navigate action into a setTimeout with 100 delay for example,it works fine, but for my scenario this is not a good idea cause the app is really lazy on edge or IE and there 100 miliseconds will be not enough.

Can you help me please with an idea?

Andrew-Lahikainen commented 8 years ago

I ran into a similar issue where if I clicked two route links in quick succession, they would start looping back and forward. I presume it was happening because my routerOnActivate promise hadn't resolved by the time another routerOnActivate had been called (I don't know what's happening internally).

I hacked around this by doing something like this:

$ctrl.$routerOnActivate = function(next) {
    $timeout().then(activate);

    function activate() {
        // your onActivate code, i.e. $ctrl.$router.navigate(['abcd'])
    }
}

I don't think you need more than a 0 second delay but definitely use $timeout.

iliesalex89 commented 8 years ago

Thanks a lot for your help. Sorry for late feedback. I fixed it few weeks ago using a watch on rootScope until navigating property on rootRouter is false and everything works fine without any timeout. I created a custom method, something like this:

 customNavigate($childRouter) {
    return (route) => {
        if (!this.$rootRouter.navigating) return $childRouter.navigate(route);
        var stopWatching = this.$rootScope.$watch(
            () => {
                return this.$rootRouter.navigating;
            },
            () => {
                if (!this.$rootRouter.navigating) {
                    stopWatching();
                    $childRouter.navigate(route);
                }
            });
    };
}