angular: Using router.navigate to navigate to another component does not invoke the onInit method

Hi I am implementing a project in angular . and i am using the version ng-version=“4.3.0” Here i am redirecting the app to another component doesnt invoking the oninit method

Here is my sample code

`fblogin() {
        const provider = 'facebook';
        this.socialloginservice.onFacebookLogin().subscribe(
            response => {
                this.authService.socialSignup(provider, response).subscribe(res => {
                    console.log(this.authService.getToken());
                    console.log('redirecting');
                    this._router.navigate(['/register-step2']);
                });

            },
            error => console.log(error)
        );
    }` 

I am redirecting the app to another route in the success of an http service call

Current behavior

In Register step2 component

constructor(private authenticateservice: AuthenticateService,
              ) {
     console.log('ok Working');

  }

ngOnInit() {
 //not working
}

Expected behavior

constructor(private authenticateservice: AuthenticateService,
              ) {
     console.log('ok Working');

  }

ngOnInit() {
 //should work
}

i have checked for this issue in the web and i found the articles like below saying to add below scripts

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script> <script src="node_modules/systemjs/dist/system.js"></script>

but i didn’t have such folders in my node modules. i am not getting where to import these files and from where to import. Please let me know where i am missing https://github.com/angular/angular/issues/4809

Environment


Angular version: 4.3.0


Browser:
- [ ] Chrome (desktop) latest version 

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 30
  • Comments: 38 (4 by maintainers)

Commits related to this issue

Most upvoted comments

I have the same issue. Angular is running in a Cordova app for iOS. I tried the router-version 4.1.3 (like @lecogiteur said), and it worked. With my current version of 4.3.1 it didn’t work.

The method @chinna-magapu provided (putting it into a ngZone.run call), works for me:

this.ngZone.run(() => this.router.navigateByUrl(url))

Hopefully there will be a fix soon.

Hi I have solved my issue by doing this while navigating ,

this.authService.socialSignup(provider, response).subscribe(res => { console.log(this.authService.getToken()); console.log('redirecting'); **this.zone.run(() => this._router.navigate(['/register-step2']));** });

Reference : https://stackoverflow.com/questions/35936535/angular-2-ngoninit-not-called

Thanks.

Hi,

We have the same issue. Looks like it’s working fine with Chromium but not with Firefox. The broken versions seem to be from the 4.2.0 upward (router package only), since the 4.1.3 works fine as well.

Thanks for your help.

I am also experiencing the same problem. Angular 4.2.4 here. Replacing the navigation via routerLink with this.ngZone.run(() => …)) solves the problem.

I am also loading data subscribing from a google/facebook authentication result (using angular2-social-login 3.1.1). Similar to what @caztial mentioned above.

Same issue in Angular 4.4.4 while working with Facebook JS SDK and is resolved by using NgZone. Hope Angular Team would find a better solution soon.

ISSUE

FB.getLoginStatus(res => {
      if (res.status == 'connected') {
        this.appService.cacheData('accessToken', res.authResponse.accessToken);
        
        // BUG: FacebookAnalysis component (ngOnInit / ngAfterViewInit) will not get called
        // moreover, FacebookAnalysis component class data members
        // will not get passed to component template
        this.router.navigateByUrl('/facebook-analysis');
      }
});

FIX

FB.getLoginStatus(res => {
      if (res.status == 'connected') {
        this.appService.cacheData('accessToken', res.authResponse.accessToken);
        
        // FIX: replacing with ngZone everything works just fine.
        this.ngZone.run(() => {
          this.router.navigateByUrl('/facebook-analysis');
        });
      }
});

Same problem in Angular 5.2.10. Still not working anything for me.

Same problem for me i use Angular 6 on Ionic v4 this code in goBach() function doesn’t work.

 goBack() : void{
      this.ngZone.run(() => {
        this.router.navigate(['/users'], { relativeTo: this.route });
      });

Someone can help me please

same issue for Ionic 4 and Angular 7

Same issue with Angular 7 and PrimeNG

Same issue angular 7 and Ionic 4

I’ve had the same issue and the answers in these thread helped me. Just a bit of input.

This works perfectly without having any 3rd party calls

submit(): void {

	var self = this;

	self.router.navigate(['/home']);
}

After you’re adding 3rd party calls this goes sideways

submit(): void {

	var self = this;

	self.router.navigate(['/home']);

	let data = { title: this.title, content: this.content };

	this.ipfsService.ipfs.addJSON(data, (err, hash) => {

		if (err)
			console.log(err);

		console.log("Saved to IPFS", data);
		console.log("IPFS hash:", hash);

		self.hashStoreContract.instance.save(hash, { gas: 300000 }, function (err, bidResult) {
			if (err) {
				console.log(err);
			} else {
				console.log('hash saved in blockchain!');

				self.router.navigate(['/home']);
			}
		});
	});
}

So to fix it, I’ve added NgZone

import { Component, OnInit, NgZone } from '@angular/core';

...

submit(): void {

	var self = this;

	let data = { title: this.title, content: this.content };

	this.ipfsService.ipfs.addJSON(data, (err, hash) => {

		if (err)
			console.log(err);

		console.log("Saved to IPFS", data);
		console.log("IPFS hash:", hash);

		self.hashStoreContract.instance.save(hash, { gas: 300000 }, function (err, bidResult) {
			if (err) {
				console.log(err);
			} else {
				console.log('hash saved in blockchain!');

				self.ngZone.run(() => {
					self.router.navigate(['/home']);
				});
			}
		});
	});
}

Is this related to https://github.com/angular/angular/issues/10178?

I had an issue where the URL was updating in the nav bar, but the navigated page wouldn’t load. The solution from the linked issue is to do (and worked for me):

this._router.navigate(['/register-step2'], { relativeTo: this.route });

making sure you import and inject ActivatedRoute from @angular/router

Same problem for me i use Angular 6 on Ionic v4 this code in goBach() function doesn’t work.

 goBack() : void{
      this.ngZone.run(() => {
        this.router.navigate(['/users'], { relativeTo: this.route });
      });

Someone can help me please

I’ve been able to reproduce this issue when using Firebase to handle authentication

 this.$auth.login()
      .then((user: User) => {
          this.router.navigate(['dinners', user.uid]);
      });

Did not work. Instead, I would get an error about the Url Matcher not being able to make a match. If I paused the code and resumed, the app would catch up and I don’t encounter the problem. Doing

    this.zone.run(() => {
      this.router.navigate(['dinners', user.uid])
    });

Also solves the problem but is definitely a hack.

Using Angular CLI: 1.6.1 Node: 9.2.0 OS: win32 x64 Angular: 5.1.1 … animations, common, compiler, compiler-cli, core, forms … http, language-service, platform-browser … platform-browser-dynamic, router, service-worker

@angular/cdk: 5.0.1 @angular/cli: 1.6.1 @angular/flex-layout: 2.0.0-beta.12 @angular/material: 5.0.1 @angular-devkit/build-optimizer: 0.0.36 @angular-devkit/core: 0.0.22 @angular-devkit/schematics: 0.0.42 @ngtools/json-schema: 1.1.0 @ngtools/webpack: 1.9.1 @schematics/angular: 0.1.11 @schematics/schematics: 0.0.11 typescript: 2.5.3 webpack: 3.10.0

Had to resort to window.location.href = “/login”; this.afAuth.auth.signOut(); it looks like Firebase is not logging out this.afAuth.auth.signOut(); There is a newer Firebase but had to downgrade had issues with install and looks like new types. When you call the signOut and refresh all works but not the best practice, prefer to navigate back to login or signout thank you page.

To replicate the issue in my case you need to use Firebase auth (not Google email login). After you signUp with email you need to sendEmailVerification and then signOut you will not go back to the login page. If you have any navigation that uses authGuards they state you need to login but do not navigate to the login page. It’s like a dead app. It appears that the router has some type of issue. When you tell the router to navigate to to a route it should be a no-brainier “go”. Looking at the router debug it tries to go where you want and then changes it’s own back to root ('/"). Sorry it’s quite complex to post to StackBlitz. I hope the above is some help.

Using ionViewWillEnter instead of ngOnInit or AfterViewInit worked for me.

Also having the issue with 7.2.2 in ionic.

Note that the same thing happens with AfterViewInit.

@george43g Even setTimout is ‘patched’ by Angular to use microtasks / zones. So don’t be afraid of zones, and quite possibly don’t expect a ‘fix’ to this. It might just not be possible. I’ve also seen some bizarre behavior from just doing debugging alert('test') statements completely screwing up the ‘flow’ - so watch out for that too.

Zone.__load_patch('timers', (global: any) => {
  const set = 'set';
  const clear = 'clear';
  patchTimer(global, set, clear, 'Timeout');
  patchTimer(global, set, clear, 'Interval');
  patchTimer(global, set, clear, 'Immediate');
});

PS. Intermediate to advanced Angular can be even more traumatic!

Curious if your problem is ‘fixed’ by just using setTimeout(() => { router..... }, 0). That may look nicer on the eye.

Has this been fixed yet? I think the cause of the issue is quite obvious - any 3rd party method/callback/promise causes router to not work. And the only way to fix is to use NgZone. Pausing the code in the debugger and resuming it right away also makes the router work. Surely the Angular team could fix this by now? I nearly killed my whole project not being able to fix this issue for weeks. It really hurt, bad. Esp, for a newbie who’s just learning, it’s almost traumatic.

Same problem in Angular 5.2.10. Still not working anything for me.

Me too

@be-ndee solved the problem. thanks man 😃

rafalkaczmarek wrapping into zone.run is supposed to help as well.

I`m using angular 5.1.1 with foundation 6 and problem occurs for me too.

If I run redirect from jquery event like that:

$('#globalModal').on('closed.zf.reveal', () => {
     this.router.navigate(['/welcome/signIn']);
 });

angular is silently break (looks like it is redirect but not reloading). Component constructor is called but onInit method not.

But if i run this without jquery everything works perfectly fine.

Quick workaround that im not proud of is to use window: window.location.assign(‘/welcome/signIn’);

Without a reproduction for this issue, there’s not much we can do. There’s been a number of comments above requesting a reproduction, but there still isn’t one available. I’ll close this issue for now, but if someone can come up with a repro, please create a new issue and reference this one in the description.

We suggest using StackBlitz, Plunker or Github.