What is the best way to ensure that dynamic routes from the server do not fail upon refreshing?

My application's permissions are dynamically received from the server. I have implemented a solution where I modify the router tree (using Router.config) before navigating to any item's URL in my navigation bar. Here is the function that sets the routes after receiving data from the server:

setRoutes(data) {
    data.map(module => {
        module.menus.map(menu => {
            menu.programs.map(program => {
                programs.push ({
                    moduleCode: module.code,
                    menuCode: menu.code,
                    programCode: program.code,
                    programLabel: program.dsc,
                    formType: program.formType
                });
            });
        });
    });

    let children = programs.filter(program => program.formType == 'DynamicForm').map(program => {
        if(program.formType == "DynamicForm"){
            return {
                path: program.programCode,
                children: [
                    {
                        path: "edit",
                        component: UpdateRecordComponent,
                        data: { program: program }
                    }, 
                    {
                        path: "queryForm",
                        component: DynamicProgramComponent,
                        data: { program: program }
                    }, 
                    {
                        path: "add",
                        component: AddRecordComponent,
                        data: { program: program }
                    },
                    {
                        path: "",
                        redirectTo: "queryForm"
                    }
                ]
            };
        }
    });

    this.router.config.forEach(route => {
        if (route.path === "app") {
            route.children.forEach(child => {
                if (child.path === "main") {
                    child.children = [...child.children, ...children];
                }
            });
        }
    });

Everything works fine when I navigate through the app step by step. However, the problem arises when I refresh the page at a certain point or try to access it via link. The router tree becomes empty and the app throws an error (Cannot match any routes to URL segment) before I can set the routes first before the URL event starts.

I have attempted using APP_INITIALIZER but found that the Router service or any custom services are undefined when I execute the code in the APP_INITIALIZER service.

Is there a solution to my issue in Angular?

Answer №1

Instead of relying on dynamic routes, consider using Angular route guards, specifically focusing on the canActivate feature.

The canActivate function can be utilized for each route or child routes, requiring a boolean or Observable that returns a boolean value.

This approach involves having a preset list of routes. Within your route guard, you can initially retrieve permissions from the server and store them locally (such as in local storage), allowing you to verify if the user is permitted to access a particular route.

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

Display the current date in a formatted way using Angular 2

I am struggling with displaying the current date in the format I desire. The code snippet I currently have is: this.whatTime = Observable.interval(1000).map(x => new Date()).share(); When I use this code in my template like so: {{whatTime | async}} ...

Typescript filtering function that results in an empty array

Struggling with filtering an array in typescript and aurelia as I keep getting empty lists. For example, when searching for the keyword ra within the firstName property, I expect to retrieve the object with the name "Raja". Not sure where I'm going w ...

Reasons behind Angular HttpClient sorting JSON fields

Recently, I encountered a small issue with HttpClient when trying to retrieve data from my API: constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get("http://localhost:8080/api/test/test?status=None").subscribe((data)=> ...

What Could Be Causing the Failure of Protractor Webdriver Update to Run?

Recently, I attempted to utilize Protractor on a standard run of the Angular Quickstart Seed. Unfortunately, every time I try to execute Protractor or update the webdriver manually, I encounter the following error: [11:31:24] I/file_manager - creating fo ...

Using an array of objects to display data in a chart component in Angular

I am using Angular to create multiple bar charts on the screen by looping through an array of objects. In my HTML, my code looks like this: <div class="row"> <div class="col-md-5" *ngFor="let sprintCapacity of sprintCapacities"> <div ...

Received corrupted file during blob download in Angular 7

When using Angular 7, I am making an API call by posting the URL file and attempting to download it using the 'saveAs' function from the fileSaver library. The file is successfully downloading, but it appears to be corrupted and cannot be opened. ...

Can the swiping feature be turned off while the image is zoomed in?

For a project, I am utilizing the angular2-useful-swiper wrapper with iDangerous Swiper. I am seeking a way to disable the swiping functionality when an image is zoomed in. After researching the Swiper Api, I have not found any information on how to achie ...

Unable to choose Typescript as a programming language on the VSCode platform

Recently, I encountered an issue while using Visual Studio Code with TypeScript. Even though TypeScript is installed globally, it is not showing up in the list of file languages for syntax highlighting. Despite trying various troubleshooting methods such a ...

Updating reactive form fields with patched observable data in Angular

Struggling with initializing a reactive form in my component's onInit() method, as well as handling data from a service to update or create entries in a MySQL table. The issue lies in using patchValue to pass the retrieved data into the form: compone ...

Is there a way to close the MatBottomSheet by going back in the browser?

I'm currently utilizing https://material.angular.io/components/bottom-sheet/overview. I've encountered an issue where, when the bottom sheet is open and a user clicks on the back button in their browser, they are redirected away from the page tha ...

We are in the process of migrating Angular from version 7 to 16, however, we are facing an issue where one of the libraries is still stuck on version 5, causing a Module not found error related to 'rxjs-com

We recently upgraded an Angular project from version 7 to 16 and we are currently using "rxjs": "~7.8.0". Interestingly, there is no mention of rxjs-compat in the package.json file either. However, during the building process of the application, we encoun ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

Retrieving the name of the current page in ionViewCanEnter

While working with Ionic 2, I am currently facing a challenge in identifying the name of the page that triggered the navigation (PUSHER) before entering the destination page (PUSHEE). Within the PUSHEE page, I have an ionViewCanEnter function where I need ...

Determine whether an array is void, then proceed to deactivate a button

I am attempting to prevent a button from being clickable if an array is empty, but I am encountering difficulties. <button [disabled]="(users.length ==0 )?true:false">Send mass emails</button> Within the TypeScript file: users: UsersModel[]; ...

Creating a TypeScript client to interact with React components integrated within an ASP.NET MVC web application

Can we automatically generate a TypeScript client to handle data transfer between a React component and an ASP.NET MVC controller? We have a TypeScript React app that communicates with an ASP.NET Core Web API using NSwag for TypeScript client generation. ...

The package '@angular/[email protected]' is looking for a version of typescript that is greater than or equal to 2.4.2 but less than 2.6.0. However, it detected version 2.6.2 instead

Is there a way to resolve the issue with an existing Angular project? I want to use Typescript 2.6.2. @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f99a96948990959c8bd49a9590b9ccd7cbd7c9">[email protected]& ...

What is the best way to send an XML body using Angular 5 with POST method?

I am currently developing an Ionic application that needs to make REST API calls with XML as the body. However, I am facing issues in getting the call to post with XML. This is my LoginProvider where I utilize DOMParser to parse data to XML before sending ...

experimenting with a TypeScript annotation

I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue ...

How to display document files (.doc or .docx) using a byte array in Angular 4

I am facing a challenge in viewing all the attachments submitted by users. While I can easily view PDF and image files, I seem to have trouble with files having .doc or .docx extensions. Here is my current approach: let file = null; if (extension === &a ...

The custom component is not updating the NgIf directive in HTML even though it receives a boolean variable

I am struggling with a custom component that includes an *ngIf in its view to handle a boolean variable, but for some reason the *ngIf directive is not working. Here is the code snippet: Component @Input('title') titleText; @Input('backButt ...