1

Trying to redirect to a new component from one of the hooks like ngOnInit(), ngAfterViewInit() based on a param supplied. The current component is executed multiple times if the router navigate line is hit.

worked solution:

setTimeout(() -> { this.router.navigate(link)); //recently upgraded angular 3 to 4.0.0 router       

main module :

 RouterModule.forChild([
        { path: 'referrer/:vehicle/:referrer', component: ReferrerComponent },
        { path: 'referrer/:referrer', component: ReferrerComponent },
        { path: 'vehicle', component: vehicleComponent},
    ])

route: http://localhost:4200/#/referrer/vehicle1/referrer1

ReferrerComponent:

    ngOnInit() {

          this.routeObservable = this.route.params.subscribe((params) => {

               if(params["referrer"]) { // do referrer stuff;}

               if(params["vehicle"] == "vehicle1") {

                  this.router.navigate('/vehicle'); //redirect to vehicle component
               }
         });
    }

As this happens only if a redirect actually happens, not sure where to put the re route (lifecycle) exactly.

Rk R Bairi
  • 1,289
  • 7
  • 15
  • 39
  • Is it possible to do a plunker that demonstrates this? – DeborahK Aug 23 '17 at 19:33
  • If you add a method above the subscription assignment, but still inside the ngOnInit() { } block, is it called twice as well? This would tell you if your subscription is just being retriggered, or if the actual lifecycle hook was being called twice (which would be very strange). – diopside Aug 23 '17 at 19:33
  • some way or the other your observable is triggered twice – Rahul Singh Aug 23 '17 at 19:33
  • I'm not very familiar with Angular's router, but my guess is the call to router.navigate triggers an update to the subscription its hosted inside of. So it immediately gets called again. – diopside Aug 23 '17 at 19:34
  • @diopside tried redirection in block outside and even in different hook ngAfterViewInit() based on a property set in ngOnInit(), but that triggered a reload too – Rk R Bairi Aug 23 '17 at 19:46
  • Don't redirect in the block outside, just do some simple random function like console.log('') guaranteed to have no side effects, just to see if its being triggered. – diopside Aug 23 '17 at 19:51
  • @diopside it is loaded twice. it worked with a timeout is set on the redirect. May be with the version of angular route is a problem (4.0,0) – Rk R Bairi Aug 23 '17 at 20:25
  • 1
    Yeah if lifecycle hooks like ngOnInit() are being called twice, that must be an issue with the router's dynamic component creation - afraid I can't be of much help there. I don't use the angular router. It frustrated me so much I wrote my own, lol – diopside Aug 23 '17 at 20:26

0 Answers0