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

Ensure that the text is wrapped properly when implementing innerHTML functionality

Within my Angular 5 application, I am faced with a requirement to display HTML content retrieved from a database. An example of the text stored in the database is: <div><u>Documents and Files</u></div><ul><li>These docu ...

Tips for retrieving refreshed information following modifications via a POST request in Angular 2

I've scoured the web extensively, but I just can't seem to grasp how to retrieve updated data from the database. I'm currently learning Angular 2, and my predicament lies in fetching data from a table named 'branches' using PHP wit ...

Guide to sending client-to-client notifications in Angular/Ionic with Firebase Cloud Messaging

I am looking to implement client-client push notifications (not server-to-client). My goal is to send a notification when one user messages another. Is this feasible? How can I achieve this using the structure in the Firebase real-time database? Here is a ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

Can you tell me the significance of the constant variable isType = <T>(type: string) => (obj: unknown): obj is T => toString.call(obj) === `[object ${type}]`?

const isType = <T>(type: string) => (obj: unknown): obj is T => toString.call(obj) === `[object ${type}]` This function is all about determining types, but the arrows used in the syntax are confusing to me. I'm not sure what each arrow s ...

Utilize array mapping to alter the complete object

In my project using TypeScript (Angular 2), I am working on creating a "reset" method for an object array: cars [ { id: 1, color: white, brand: Ford, model: Mustang, ... }, ... ] Users have the ability to modify these objects, ...

Issue: Module 'stylelint' not found in Angular Project

I've been attempting to execute this command to validate all of the .scss files (and even tried with .css files) and I keep encountering this error. $ stylelint "apps/**/*.scss" It worked once before but not anymore, even after restarting my compute ...

Do ES6 features get transpiled into ES5 when utilized in TypeScript?

After implementing ES6 features such as template strings, arrow functions, and destructuring in a TypeScript file, I compile the code to regular JavaScript... Does the TypeScript compiler also compile the ES6 syntax, or do I need to utilize another compil ...

Tips for effectively matching a type definition pattern in TypeScript

Good evening! I'm currently working with Angular and rxjs, but I have a feeling that TypeScript is going to play a significant role in my project today. I've been exploring different methods to achieve my goal, but it's definitely challengi ...

Troubleshooting Google Authorization Issue in Angular 17: How to Fix the Error TS2304: 'google' Not Found in Angular 17

I am encountering an issue while attempting to integrate Google Auth into my Angular(+Express) application using the Google Identity Services library. Despite following the instructions provided in the Google tutorial, I am facing the error: "[ERROR] TS230 ...

The Glyphicon is failing to display on the template

I recently set up bootstrap in my VS Code environment and linked it to the styles.css file with this code snippet: @import '~bootstrap/dist/css/bootstrap.css'; Upon further inspection of the package.json, I confirmed that "bootstrap": "^4.1.1" ...

Using an external variable within an internal function in TypeScript

I am facing a situation where I have a variable outside of a function that needs to be updated, but I am unable to access it using "this" as it is not reachable at that point in the code. export class GamesDetailPage { details : any = {}; type : St ...

custom field component for react-hook-form

I have been working on creating a form field component that can be utilized at both the root form level and as a nested field. export type FirstNameField = { firstName: string; }; type GenericFormType<T, NS extends string | never = never> = NS ext ...

Is it possible to remove a complete row in Angular 2 using Material Design

JSON [ { position: 1, name: 'test', value: 1.0079, symbol: 'HHH' }, { position: 2, name: 'test2', value: 4.0026, symbol: 'BBB' }, { position: 3, name: 'test3', value: 6.941, symbol: 'BB' }, ...

TypeScript Compile Error: The property is not available in the 'IStateParamsService' type

My client project heavily utilizes TypeScript. Currently, I am encountering a technical issue. Within my HTML code, I have an anchor tag as shown below: <a class="btn btn-default mrm" ui-sref="course-detail({courseId: '{{c.Id}}'})">Detail ...

One way to display a table is by populating it with data from an API. If the table does

Within my Angular 6 application, there exists a table that displays data fetched from a web api. Additionally, I have incorporated some ngIf containers. One of these containers is programmed to exhibit a message in case the web api data turns out to be emp ...

Could a tslint rule be implemented in Typescript classes to ensure method return types are enforced?

After diving into the tslint rules here, it seems that although the typedef rule's call-signature option might be close to what I need, it doesn't address the absence of a return type. Is there a specific rule (if one exists) that can enforce re ...

Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:AngularhttpErrorHandlingExamplesrcapp'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: E ...

What is the method for deducing the return type based on the parameter type in a generic function?

Check out this code snippet featuring conditional types: class X { public x: number; } class Y { public y: number; } type DataCategory = "x" | "y"; type TData<T extends DataCategory> = T extends "x" ? X : T extends "y" ? Y : ne ...

A recursive approach for constructing a tree structure in Angular

Currently, I am working on a project involving the implementation of crud functions. To display the data in a tree-like structure, I am utilizing the org chart component from the PrimeNg library. The data obtained from the backend is in the form of an arra ...