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

Tips for accessing web API within an Angular service

Just starting out with angular and in need of some guidance on how to call my API within the angular code. Can anyone provide assistance? The API I am using is: [HttpGet,Route("api/customer/getCustomer/{name}")] public async Task<IHttpActionResult> ...

What is the process for integrating d3-selection-multi into d3?

Working with d3 V4 can be both exciting and challenging. Despite my struggles to create a custom webpack bundle with other modules, I have managed to enhance the vanilla d3 bundle by adding multi-selection functionality. To facilitate this integration in ...

Angular integration problem with aws-amplify when signing up with Google account

I am attempting to integrate AWS-Amplify(^4.3.0) with angular-12 and typescript (4.3.5). I have followed the documentation to configure amplify properly, but when trying to start the app, I encountered some amplify errors as shown below. Warning: D:\G ...

Encountering a unique webpack error while attempting to upgrade Angular from version 11 to version

Struggling to upgrade my Angular version from 11.1.1 to 12.1.1 and encountering a build error. "CustomWebpackDevServerSchema" schema is using the keyword "id" which its support is deprecated. Use "$id" for schema ID. "BuildCustomWebpackBrowserSchema" sche ...

Dependencies for Angular 5 plugins

Will the total list of dependencies for the application be a combination of all unique dependencies from Angular plugins with their own managed dependencies in Node, even if they have some overlapping dependencies? For example, if plugin 1 has 1000 depen ...

Having trouble with errors when trying to implement react-router-v6 with typescript

Having trouble with my code and receiving the following error: "Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'. Type 'null' is not assignable to type 'Element | ...

Having issues with Angular Material's mat-icon rendering weird symbols?

I'm facing an issue with an Angular material button that some users are also experiencing. In the Chrome browser, the icons are displaying incorrectly. Instead of the expected icons, strange characters are showing up. For example, the menu icon is sho ...

How can I activate a custom event on a repeated div element in Angular 2?

I am working on a project where I need to create multiple divs using an ngFor loop. When a user clicks on one of the divs, I want to add a unique class only to that specific div. Currently, I am using a boolean flag on [ngClass] as a test case, but I am u ...

Harnessing the power of Material-UI's muiThemeable with Typescript

I'm trying to access the current theme colors within a custom React component. The example I'm referencing is from Material UI http://www.material-ui.com/#/customization/themes Despite attempting various approaches, I'm unable to get Typesc ...

Here's how to retrieve a property from a union type object in Typescript without the need for type casting

I am facing a scenario with various types: export type a = { todo: string; }; export type b = { id: number; }; export type TodosAction = Action<string> & (a | b); In addition, I have a function defined as follows: function doSmth(action:To ...

Is there a way to refresh the current page in Ionic 3 when the browser is reloaded?

I have encountered a problem in my work with an Ionic 3 App. I am looking for a solution where the browser will refresh the current page instead of redirecting me to the home page. Is this achievable? I attempted to solve it using the following code: thi ...

The issue arises when the desired image size is not reflected correctly on the background after changing

I've been working on a basic image slideshow where the background image changes based on user selection. However, I've noticed that when I change the image for the first time, the backgroundSize: cover property seems to disappear. Even if I try c ...

Exploring Attack on Titan alongside the concept of dynamic route templates in coding

I am currently working on creating a factory for an UrlMatcher. export const dummyMatcher: UrlMatcher = matchUrlFn(sitemap as any, 'dummy'); export const routes: Routes = [ { matcher: dummyMatcher, component: DummyComponent }, { path: &apos ...

Step-by-step guide on setting up cosmosDB databases and containers in azure functions with the node sdk

In my current setup, I have database initialization code that runs on every function request, impacting performance negatively. How can I verify the existence of a container in Cosmos DB using the node SDK? It's recommended to establish static conne ...

The absence of typings.json in Typescript is creating an issue

As of now, I am encountering the following error during compilation: typings.json is missing In my existing packages.json, I have included the following dependency: "devDependencies": { "typescript": "^2.6.1", ... } Do you have any suggestion ...

The animation of the splash screen in Angular is quite jarring and lacks fluidity

I am experiencing some issues with my angular splash screen animation. It works perfectly when there is no activity in the background, but when I simulate a real-life application scenario, the animation becomes stuttered, choppy, or sometimes does not anim ...

The function getServerSideProps does not return any value

I'm a beginner with Next.js and I'm currently using getServerSideProps to retrieve an array of objects. This array is fetched from a backend API by utilizing the page parameters as explained in the dynamic routes documentation: https://nextjs.org ...

React.js with Typescript is throwing an error stating that a property does not exist on the child component

Currently, I am working with React in conjunction with typescript 2.3.4. I keep encountering the error TS2339: Property 'name' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'. This issue arises wh ...

Error: Unable to Locate Module (Typescript with baseUrl Configuration)

Struggling to implement custom paths in my TypeScript project, I keep encountering the "webpackMissingModule" error due to webpack not recognizing my modules. I've attempted various solutions without any success. Any suggestions or ideas? Some packa ...

Angular and Webpack combined to output the build project to the specified output path

In the process of integrating my Angular client-side application with a server-side written in Spring, I am seeking a way to build the UI project and store it in the /target directory within the backend portion for easy installation using Maven. My uncer ...