To navigate in Angular, you can either refresh the page or manually enter the desired path, which will automatically lead you back

I recently encountered an issue while working on my Angular 11 project. Everything was running smoothly until I faced the following problem:

When using routerlink to navigate to a specific path, it redirects correctly. However, if I attempt to access that path manually by entering "localhost:4200/reunion" in the browser, it initially redirects to an empty path and then redirects to the home page at "localhost:4200/tableau_de_bord".

Below is a snippet of my app.routing.ts file:


const routes: Routes = [  
  {
    path: 'connexion',
    component: ConnexionComponent
  },
  // ... other paths
  {
    path: '',
    redirectTo: 'tableau_de_bord',
    pathMatch: 'full',
    canActivate: [AuthGuard],
  },
  // ... other paths
];
@NgModule({
  imports: [
    CommonModule,
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
})
export class AppRoutingModule { }

This is what my admin-layout.routing.ts looks like:


export const AdminLayoutRoutes: Routes = [
  { path: "", redirectTo: "tableau_de_bord", pathMatch: "prefix" },
  { path: "tableau_de_bord", component: DashboardComponent },
  {
    path: "reunion",
    component: ListReunionComponent,
    canActivate: [AuthGuard],
  },
  // ... other routes
];

And here is my admin-layout.module.ts:


@NgModule({
  imports: [
    // ... other imports
    RouterModule.forChild(AdminLayoutRoutes),
    // ... other imports
  ],
})
export class AdminLayoutModule { }

The main issue I'm facing is with refreshing or reloading the page and ending up at the correct path. Accessing paths defined in app.routing.ts works fine, but when trying paths from admin-layout.ts like "localhost:4200/reunion", it redirects back to the homepage "localhost:4200/tableau_de_bord". Even after removing canActivate from both routing files, the issue persists.

I also tested this scenario in private browsing mode without success. One thing worth mentioning is that I had "" in my index.html file.

Update: Here is the AuthGuard code being used:


@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  public url:any;
    constructor(private router: Router,private authService: AuthServiceService) {}

   canActivate( next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        let url: string = state.url;
        return this.checkUserLogin(next, url);
    }
  
    checkUserLogin(route: ActivatedRouteSnapshot, url: any): boolean | UrlTree {
        if (this.authService.isLoggedIn()) {
          const userRole = this.authService.getRole();
          if (route.data.role && route.data.role.indexOf(userRole) === -1) {
            this.router.navigate(['/connexion']);
            return false;
          }
          return true;
        }
        this.url = url;
        this.router.navigate(['/connexion']);
        return false;
      }
}

Answer №1

There are multiple redirects, but we only require one to redirect to tableau_de_bord.

const routes: Routes = [  
  {
    path: 'connexion',
    component: ConnexionComponent
  },
// ...
  {
    path: '',
    component: AdminLayoutComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: '',
        loadChildren: './shared/admin-layout/admin-layout.module#AdminLayoutModule'
      }]
  },
  {
    path: '**',
    redirectTo: 'tableau_de_bord'
  },

];

@NgModule({
  imports: [
    CommonModule,
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  exports: [
  ],
})
export class AppRoutingModule { }

Next, we rearrange the redirects from the lazy loaded route as they are already taken care of by the parent.

export const AdminLayoutRoutes: Routes = [
  { path: "tableau_de_bord", component: DashboardComponent },
  {
    path: "reunion",
    component: ListReunionComponent,
    canActivate: [AuthGuard],
  },
  { path: "", redirectTo: "tableau_de_bord", pathMatch: "prefix" },
// ...
];

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

Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined Please refer to the image for a visual representation of my problem. I'm not sure what I might be overlooking, so any help would be greatly appreciate ...

Guide to slicing strings specifically with numerical characters at the end

I've encountered a challenge. I need to slice the last two characters in a string, but only for strings that contain numbers. I attempted using "nome": element.nome.slice(0,-2) and now I require some sort of validation. However, figuring out how to do ...

Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript. To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images. Here is the project structure: https://i.stack.imgur.com/xfIYD.pn ...

Get the date string formatted for an Angular2 date range picker

In my Angular2/Spring web application, I am utilizing a calendar from the following sources: https://www.npmjs.com/package/ng2-daterangepicker http : // www. daterangepicker . com/ The issue I am encountering is with formatting the date output. Accordin ...

Tips on how to effectively unit test error scenarios when creating a DOM element using Angular

I designed a feature to insert a canonical tag. Here is the code for the feature: createLinkForCanonicalURL(tagData) { try { if (!tagData) { return; } const link: HTMLLinkElement = this.dom.createElement('link'); ...

What is the best way to retrieve the names of "string" properties from an interface in TypeScript?

Explore Typescript playground I aim to extract the string characteristics from SOME_OBJECT and form them into a union type. Thus, I anticipate STRING_KEYS to signify "title" | "label" interface SOME_OBJECT { title: string, ...

Top Method for Dynamically Adding Angular Component on Click Action

As I develop my website, I am faced with the challenge of incorporating multiple components. One specific feature involves allowing users to dynamically add a component of their choice to the "Home" page when they click a button. I have explored three diff ...

aiplafrom struggles to establish a customer using Vite alongside Vue and TypeScript

I'm currently experimenting with Gemini Pro on Vite + Vue + TS, but I encountered an issue when attempting to create an instance of PredictionServiceClient. The error message displayed is Uncaught TypeError: Class extends value undefined is not a cons ...

Manipulate div display based on select value in Angular2 using [(ngModel)] with ion-select

I am currently working with ionic2 and angular2 using JavaScript, not TypeScript. I have two inputs: one for text and the other a select dropdown. My goal is to hide the text input if the value selected in the dropdown is 'more'. How can I achiev ...

node directing traffic to a webpage

Here is the layout of my folders: root admin index.html bootstrap.css ... ... app.js When I run node app.js with Express 4, routing functions correctly. However, when trying to access this file: http://localhost/admin/index ...

encountering an issue during the installation of a node package

Encountering this error while trying to install npm i npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bfaf5fceef7fae9b6f2f6fafcfeb6fefff2eff4e9dbabb5abb5aa">[email protected]</a> npm ERR! ...

Unable to locate angular moment components

I encountered an error while trying to build my angular project using npm start. I attempted to install dependencies using the yarn command, but it didn't solve the issue. Below is the error message that I am receiving: ERROR in ./src/AppPreBootstra ...

When is it appropriate to utilize the produced HTML code?

Imagine a scenario with a template structured like this: <a id="registerLink" *ngIf="!isLoggedIn" #registercontainer>Login</a> Underneath, we have the following component: @ViewChild('registercontainer') registercontainer: ElementR ...

Tips for ensuring the Google Maps API script has loaded before executing a custom directive on the homepage of an Angular website

Issue - I am facing issues with Google Maps autocomplete drop-down not working on my website's main page even after parsing and loading the Google Maps API script. The problem seems to be a race condition on the main page of my website, specifically i ...

Enhancing React with TypeScript: Best Practices for Handling Context Default Values

As I dive into learning React, TypeScript, and Context / Hooks, I have decided to create a simple Todo app to practice. However, I'm finding the process of setting up the context to be quite tedious. For instance, every time I need to make a change t ...

Having trouble getting Laravel and Angular to filter data by categories?

I am currently developing an ecommerce project using Laravel and Angular. I have products and brands associated with these products. In my function to retrieve the products in Laravel, I have used a nullable parameter like this: public function index($bran ...

Unable to identify the project or target specified in the Architect command for angular4

Having an issue with running this command: ng build --target=production --base-href /, I encountered the following error: Error: Unable to identify project or target for Architect command. at MergeMapSubscriber._loadWorkspaceAndArchitect.pipe.oper ...

Mentioning a specific key more than once within a data structure

Sorry for the vague title, I'm struggling to articulate this idea. Here is a type definition that I have: type Foo = { a: number, b: string, c: boolean, } I am looking to utilize this type as follows: type FooInfo = { property: keyof Foo, ...

Issues arise when attempting to connect NgRx Angular application with Redux DevTools

Currently, I am following a tutorial to learn about ngRx Entity. However, I am facing an issue where my Redux dev tools are not indicating that they are active in the app using Redux. Additionally, the data I expect to see in the dev tools is not showing u ...

Terminate the operation of an active script tag within Angular 11

At the moment, my Angular component is utilizing the Renderer2 library to insert a series of script tags into the DOM. These scripts are sourced externally and I am unable to alter their content. Below is a snippet where the scripts array contains the link ...