The application's functionality is interrupted when router.navigate() is called within the .subscribe method

I am having an issue with user navigation on my application. After successfully signing in, users get redirected to the home page (/), but they are unable to navigate by clicking any links on that page.

Upon further investigation, I discovered that moving

this.router.navigate(['/'], { relativeTo: this.route })
out of the subscribe block in the login method solves the problem and all functionality works as expected.

It seems there is an issue with calling this.router.navigate from the subscribe block. Can anyone help me figure out what's causing this behavior? Thanks.

Note: I found a similar question on StackOverflow here. The suggested solution of local assignment for router did not work. Angular version - 11

login(pwd: any){
    this.loginService.login(usrname,pwd).subscribe(
    (response) =>
     {
          console.log("success executed");

          this.router.navigate(['/'], { relativeTo: this.route }).then(x => console.log("????? "+x));
        return;
    },
    (error) => 
    {
         console.log("ERRR  == "+JSON.stringify(error));

    }
   );

}

UPDATE

APP ROUTING MODULE.

  { path: '', loadChildren: () => import('./home-page/home-page.module').then(m => m.HomePageModule) , pathMatch:"full"},

  {
    path: 'signup',
    loadChildren: () => import('./Reg/Reg.module').then(m => m.RegModule) 

  },

RegRoutingModule

import { SignUpComponent } from './sign-up/sign-up.component';

const routes: Routes = [
  { path: '', component: SignUpComponent },
  { path: 'signin', component: SignInComponent },

];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class RegRoutingModule { }

When users decide to sign in, they land on the Signup page (SignUpComponent ), and then click on the link SIGN IN (SignInComponent ). Both are lazy loaded modules.

The Homepage component is also a lazy loaded module.

UPDATE 2

HomePageRoutingModule

import { HomePageComponent } from './home-page.component';


const routes: Routes = [{ path: '', component: HomePageComponent },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class HomePageRoutingModule { }

UPDATE 3

<div>
       <a [routerLink]="['profile/8']" routerLinkActive="active"> Go to Page 2</a>

       <button (click)="navigateToProfile(profId)">
                                    profile
       </button>
   </div>




navigateToProfile(profId: number) {

this.zone.run(() => {
  
  this.router.navigate(['profile/'+profId]);

});

Note: Trying without using this.zone had the same result. Could this issue be specific to Angular 11?

Note: This only happens when navigating from subscribe; otherwise, it functions correctly.

UPDATE 4

Web service

 SignIn(signinModel: SignIn): Observable<boolean> {

    return this.httpClient.post<SignInResponse>(this.host + "/api/Sign", JSON.stringify(signinModel), { responseType: "json" })
      
     .pipe(map(e => {
       localStorage.setItem("user", e.token);
       return e != null ? true:false;
     }));
    
  }

If I comment the line `` it all works fine. Adding the token to localstorage seems to be the problem.

Answer â„–1

Latest Update:

localStorage.setItem("user", e.token);

Is e.token considered a string or an object? If it's an object, you should use JSON.stringify() and JSON.parse() to serialize and de-serialize it since localStorage and sessionStorage can only store string key/value pairs according to the documentation.

If you modify your code like this, it may resolve the problem:

.pipe(map(e => {
       localStorage.setItem("user", JSON.stringify(e.token));
       return e != null ? true : false;
     }));

and later retrieve it like so:

const user = JSON.parse(localStorage.getItem("user"));

Previous Update:

After some troubleshooting, it seems that the navigation issues occurring after reaching the Home page might be related to the pathMatch:"full" setting in app-routing.module.ts. While I couldn't reproduce the subscription issue you're facing, it appears to be connected to the relative routing system. You could try commenting out the pathMatch:"full" flag to see if that resolves the problem.

I've created a test project on stackblitz to simulate your scenario. Feel free to review it for any discrepancies in your code: https://stackblitz.com/edit/angular-ivy-aqrxbc?file=src/app/app-routing.module.ts


The issue likely stems from route configurations or unexpected behavior from route guards.

Could you specify if you are using eager or lazy loading for your HomeComponent? Sharing the module where you configure your routes could help identify the underlying problem.


I'm also puzzled by the necessity of { relativeTo: this.route } during navigation. Typically, no route scoping should be required at this stage.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I prevent right-clicking with Ctrl+LeftMouseClick in Firefox on MacOS?

I'm looking to implement a shortcut using Ctrl+LeftMouseClick in my React project. It functions perfectly on Chrome on my Mac, but in Firefox the shortcut initiates a right mouse click (event.button = 2). I believe this may be due to MacOS's Rig ...

Explore the route parameter in Angular 2

Trying to transfer a variable between two components using route parameters? In the first component, an id is sent using this function: sendId(id : string) : void { this.router.navigate(['/component2', id]); } The routing module setup inclu ...

Bringing in a module that enhances a class

While scouring for a method to rotate markers using leaflet.js, I stumbled upon the module leaflet-rotatedmarker. After installing it via npm, I find myself at a loss on how to actually implement it. According to the readme, it simply extends the existing ...

Passing data to a redirected route in Angular using the redirectTo parameter

Is there a way to send the "data" to the home component only when redirected from an old path, and not from an empty path? const routes: Routes = [ {path : '', redirectTo:'home'}, {path : 'oldPath', redirectTo:&apo ...

Perform an Angular HTTP request and await responses from multiple sources

I'm currently working with Angular 11 and looking to make an HTTP call to an API that will trigger a server-side process. Here's the code for the HTTP call: processData(data) { return this.httpClient.post('https://myurl/api/process&apos ...

The Nestje subscription is encountering a NULL value and displaying an error message stating: "Non-nullable field Subscription cannot be returned as null."

I attempted to implement a Subscription in my nestjs project with GraphQL, but encountered the following error message: Cannot return null for non-nullable field Subscription Below is the code snippet: //* ~~~~~~~~~~~~~~~~~~~ Subscription ~~~~~~~~~~~ ...

Obtain the selected portion of text value using Angular 2

In order to create a basic text editor that allows users to make selected text bold, follow these steps: Start by setting up a textarea with the value "Super text". Next, select a portion of this text (such as "Super"). But how can you retrieve the selec ...

Mocking multiple services and their constructors in an Angular 2 TypeScript Jasmine test component

I've got this login component code snippet that I need help testing in Angular. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@ ...

The symbol 'submitted' has not been declared

I have been working on implementing client-side validation in Angular using ReactiveForms. I encountered an error stating "Identifier 'submitted' is not defined. 'FormGroup' does not contain such a member" on this line: <div *ngIf=&q ...

Creating dynamic key objects in TypeScript with index signatures: A beginner's guide

How can the code be optimized to automatically initialize a new product type without adding extra lines of code? Failure to initialize the variable results in a syntax error. enum ProductType { PC = 'pc', LAPTOP = 'laptop', TV ...

What is the best way to properly include a parameter in my Angular 7 routing configuration?

I'm currently working on enhancing the detail section of my E-commerce platform. Here are the two paths I am using: { path: 'items', component: ItemListComponent}, { path: 'items/details/:id', component: ItemDetailComponent}, Wit ...

Encountered a XHR error (404) while attempting to load the script from https://unpkg.com/[email protected]/operators/index.js/first

Struggling with implementing the Google Material input control in angular2, I keep encountering a recurring error in the browser console. https://i.stack.imgur.com/Q5YFA.png: Upon inspecting my 'node_modules' directory, I noticed the presence o ...

When trying to set the focus on the first item in a list using HTML and Angular, the focus unexpectedly shifts to the second

I've been tackling a UI requirement where the focus needs to be set on the first element of a list item constructed from an array of objects when the tab key is pressed for the first time. Subsequent tab key presses should cycle through the list items ...

Discover the solution for resolving the issue of HttpErrorResponse 405 not permissible

I am currently managing a website on a VPS that relies on Flask as the backend API server, Angular for the frontend, and Nginx as a reverse proxy. The Nginx has SSL installed, but I am encountering an issue where I can only connect to the Flask server usin ...

Retrieving information from Next.js and Typescript with the help of getStaticProps

I've been working on a personal project with Next.js and TypeScript. I'm attempting to fetch data from an API and then map the items, but I'm running into issues. When I use console.log, it returns undefined. The file is located in the pages ...

Transitioning to mui5's sx prop instead of makeStyles is generating a typescript error - none of the overloads match this call when passing an object with

I encountered an issue while converting a component to mui 5. Here is the original code snippet: const useStyles = makeStyles({ imageContainer: { display: "flex", width: "65%", float: "left", marginRight ...

Can someone explain how to create a Function type in Typescript that enforces specific parameters?

Encountering an issue with combineReducers not being strict enough raises uncertainty about how to approach it: interface Action { type: any; } type Reducer<S> = (state: S, action: Action) => S; const reducer: Reducer<string> = (state: ...

The server has access to an environment variable that is not available on the client, despite being properly prefixed

In my project, I have a file named .env.local that contains three variables: NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY=pk_test_<get-your-own> MAGIC_SECRET_KEY=sk_test_<get-your-own> TOKEN_SECRET=some-secret These variables are printed out in the file ...

Angular2: The NgFor directive is designed to work with Iterables like Arrays for data binding

I'm currently working on a university project to develop a web application consisting of a Web API and a Frontend that interacts with the API. The specific focus of this project is a recipe website. Although I have limited experience with technologies ...

ERROR: Unable to call function getTime in Typescript

While working on my function in Typescript, I encountered an issue with two sets of data in the database - date and time, both expecting strings. When users select a date, I trigger a POST request to set the time for them. To handle this scenario, I creat ...