The Angular router is directed to an empty URL path instead of the specified URL

I have encountered a strange issue while developing my angular app which involves the router functionality. All routes were working perfectly fine until I discovered that after a successful login, instead of navigating to the '/admin' path as intended, the router defaults back to '/' for some reason. Here is the relevant code snippet:

//login.component.ts
if (this.authService.getUserRole() == 'user' || this.authService.getUserRole() == 'agent') {
window.location.assign('/')
} else if (this.authService.getUserRole() == 'admin') {
window.location.assign('/admin')
}



//app.routing.ts
import {AdminComponent} from './admin-master/admin/admin.component;
import {HomeComponent} from './home/home.component;

const appRoutes: Routes = [
{path: '', component: HomeComponent, pathMatch: 'full'},
{path: 'admin', component: AdminComponent, canActivate: [AuthGuard], data: {permission:{only: ['admin']}}}
]

EDIT: (added auth.guard.ts)

//auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

      const permission = next.data["permission"];

      if(this.authService.isLoggedIn() &&
      permission.only.includes(this.authService.getUserRole())) {
        return true;
      } else {
        this.router.navigateByUrl('/logout');
      }
    
  }
  
}

The Issue:

  1. Despite a successful login, the router redirects users to an empty URL instead of the specified URL set in the login.component.ts file.

  2. This leads to elements from the home.component.html being displayed in the admin dashboard, which should not be happening.

In summary, how can I ensure the routing functions correctly? Is there an error in my approach? Thank you for your assistance!

Answer №1

You have the option to utilize Router in place of window.location.assign for navigating to various URLs.

For instance:

import { Router} from '@angular/router';

/* Login Component */

constructor(private router: Router, private authService: AuthService) { }

navigate() {
    if (this.authService.getUserRole() == 'user' || 'agent') {
        this.router.navigateByUrl('/')
    } else if (this.authService.getUserRole() == 'admin') {
        this.router.navigateByUrl('/admin')
    }
}

Refer to the documentation https://angular.io/api/router/Router

Answer №2

Substitute window.location.assign('/admin')

using

this.router.navigate(['../admin'], {relativeTo: this.route});

router : Router route : ActivatedRoute

I trust this meets your requirements.

Answer №3

Are you certain you are being directed to the admin page? I have a hunch that your code is incorrect.

if (this.authService.getUserRole() == 'user' || 'agent') {
    window.location.assign('/')
} else if (this.authService.getUserRole() == 'admin') {
    window.location.assign('/admin')
}

It should be structured like the following, otherwise the first condition will always be true due to || 'agent'

const role = this.authService.getUserRole();
if (role  === 'user' || role === 'agent') {
    window.location.assign('/')
} else if (role  === 'admin') {
    window.location.assign('/admin')
}

I also recommend using === for both value and type checking.

Answer №4

Upon reviewing my app.routing.ts file, I noticed that eliminating {useHash: true} from the code snippet below led to a successful URL redirect. The issue arises when adding {useHash: true}, as it appends an additional /# to the URL, causing it to default to a blank page since no matching routes are found.

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, { useHash: true, enableTracing: true });

To address this, I made the following adjustment:

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

Kindly note that I also removed enableTracing: true in order to tidy up the console output.

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

Utilizing ternary operators in Angular 6 tables

I need to dynamically display certain amounts based on the comparison of two interest values. Here is the logic: <td *ngIf="subTable.flexitaxMaxPaymentDate"> subTable.flexitaxMaxInterest > subTable.IRDInterest ? {{subTable.maxAmou ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Chrome fails the karma tests while phantomjs passes them

I've been struggling with this issue for some time now and can't seem to find a solution. I'm working on an Ionic 2 project that utilizes Angular 2's testing environment. When I run 'ng test' using Karma's Chrome launcher ...

"Is there a way to dynamically remap an array only when there are changes

One of the challenges I am facing is with a component called Page, which contains two components - Editor and Preview. Page has an array called items. [ { value: 0, text: 'Item 1' }, ... ] This array items is passed ...

Guide on importing absolute paths in a @nrwl/nx monorepo

I am currently working on a @nrwl/nx monorepo and I am looking to import folders within the project src using absolute paths. I attempted to specify the baseUrl but had no success. The only solution that did work was adding the path to the monorepo root ts ...

Evaluating function declaration - comparing interface to type alias

Here is a function that I need to create a validator for: function (n: number) { return {s: n}; } I have come across two options for creating the validator: Option 1: Interface interface ValidatorFnInterface { (n: number): { [key: strin ...

Heroku encounters issue with Node.js and Angular build process

I have encountered an issue with my app deployment. Everything works fine locally, but when I try to deploy, the build fails and generates the following output log: -----> Node.js app detected -----> Creating runtime environment NPM_CONFIG_ ...

Steps for removing the style when a button is clicked

Inside the ngFor loop, I have a button that I am styling as shown below. <div *ngFor="let component of componentList; let index = index"> <button type="button" id='Button{{index}}' name='Button{{index}}' ...

Setting up Angular on your Mac

Recently, I attempted to set up Angular on my macOS system. After confirming that I have npm 5.6.0 and node 8.11.1 installed, I proceeded with sudo npm install -g @angular/cli. It appeared to be successful at first, but upon running ng --version, the follo ...

ESLint version 8.0.0 encountered an error while attempting to fetch the '@typescript-eslint' plugin

Hey there, I'm in need of some assistance. I encountered an error while trying to build a project. Uh-oh! Something didn't go as planned! :( ESLint: 8.0.0 TypeError: Failed to load plugin '@typescript-eslint' specified in ' ...

The best approach for sending parameters to the parent class in TypeScript for optimal efficiency

What's the optimal solution to this problem? I really appreciate how we can specify attributes in the constructor and TypeScript takes care of handling everything to assign values to the props in JavaScript - like I did with 'department' her ...

Populating a Modal Popup with an Angular 2 Module

I am currently implementing angular 2 with bootstrap. On my dashboard page, I have a specific requirement where when a user clicks on any link, a new module should appear in a modal popup. Can you provide guidance on how to accomplish this task? Since my ...

Leverage the power of forkJoin alongside activatedRoute

One of the observables I'm working with is the following: formData$ = forkJoin([ this.httpService.getProgramsLevelsList(), this.httpService.getProgramsTypesList(), this.httpService.getQuestionnaireReasonsList() ]).pipe( tap((res: any) => ...

In regards to receiving updated data with Angular 4

As a newcomer to Angular4, I have a question regarding fetching subscribed data. Within this component, there is a method called makeTableInfo(). This method is used to generate a primeng turbotable. I am trying to access column data and row data within ...

Utilizing directives while initiating dynamic components

I've been exploring the capabilities of dynamically creating components using the ComponentFactoryResolver. const factory = this.componentFactoryResolver.resolveComponentFactory(FooComponent); const component = this.templateRoot. ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Angular's two-way binding feature does not seem to be updating the value for date

In my Angular - Dotnetcore 2.0 form, users are required to update their demographic information including their birth date. Initially, I was using the following code snippet to display the birthdate: <input id="dateOfBirth" type="date" class="form-cont ...

A Project built with React and TypeScript that includes code written in JavaScript file

Is it an issue when building a React project with Typescript that includes only a few JS components when moving to production? ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...

How can we incorporate methods using TypeScript?

I'm currently diving into TypeScript and encountering some challenges when trying to incorporate new methods into the DOM or other pre-existing objects. For instance, I'm attempting to implement a method that can be utilized to display colored te ...