Search code examples
angularangular-ui-routerngoninit

How to redirect to a new component in ngOnInit


I am making an Angular component that the user accesses by clicking a link sent to their email, which contains their user id. I need to make it so that it automatically redirects them to the admin page if they have already completed their registration. However, it seems that using router.navigate inside the ngOnInit event doesn't work, giving the error

Error: Uncaught (in promise): Error: BrowserModule has already been loaded.

Here is the code:

ngOnInit() {
this.activatedroute.params.subscribe(params => {
  this.API.getUserData(params['id']).subscribe(res => {
    console.log(res);
    this.item = res;
    sessionStorage.setItem('USER_ID', this.item._id);
    if (res["registry_complete"]){
      this.router.navigate(['/user-admin']);
    } else {
    }
  });
});
}

How do I accomplish this?

EDIT: Despite what the error says, BrowserModule is only imported once, in the main module. If the "this.router.navigate(['/user-admin']);" is removed, the code runs fine. It also runs fine outside of the ngOnInit or constructor functions. I suspect the reason for this error is because router.navigate attempts to load the main module again, and since the page is in the middle of loading it therefore imports BrowserModule twice - but if this is the case, how does one redirect this way in Angular?

EDIT: It was actually a problem in the user-admin routing module.


Solution

  • The error says that somehow, you've imported BrowserModule in your apps more than once. As specified in docs, the BrowserModule module must be imported in the root module of the app:

    Do not import BrowserModule in any other module. Feature modules and lazy-loaded modules should import CommonModule instead. They need the common directives. They don't need to re-install the app-wide providers.

    Also, NoopAnimationsModule and BrowserAnimationsModule contain BrowserModule, so if you're importing one of them, you need to remove importing BrowserModule (if you have one).