Issues with Angular Routes handling JSON array routes

Encountering an Issue with Angular Routing

I'm relatively new to Angular and making good progress. I want Angular's routing functions to be dynamic so I created a small api for Angular to fetch from, returning an array. However, when I iterate over the array, the contents are not being applied when loading them into the Routing Module. Strangely, if I use the same method to load hardcoded routes, it works perfectly!

When I try to access urls like cms/bla or cms/dashboard, everything works fine. But any other url is not recognized. The value of [i]['path'] in the array is definitely a string. For example, one of the strings is 'cms/login' but Angular returns it as not found. Am I overlooking something crucial here?

Upon reviewing the console, it displays: (3) [{...}, {...}, {...}]. When I inspect its contents, all my routes are present including the hardcodes ones at the very bottom.

Snippet of My Code

import { ApiResult } from './objects/api';

import { DashboardComponent } from './dashboard/dashboard.component';

import { NgModule } from '@angular/core';
import { RouterModule, Routes, } from '@angular/router';

import { environment } from '../environments/environment';

const routes: Routes = prepareRoutes();

function prepareRoutes() {
  const newRoutes: Routes = [{path: 'cms/bla', component: DashboardComponent}];
  newRoutes.unshift({path: 'bla', component : DashboardComponent});
  newRoutes.unshift({path: 'cms/dashboard', component : DashboardComponent});

  fetch(environment.apiUrl + '/routes/').then((value: Response)  => {
    return value.json();
    }).then((routeResults: ApiResult) => {
    for (let i = 0; i < routeResults.data.length; i++) {
      newRoutes.unshift({path: routeResults.data[i]['path'], component: DashboardComponent});
      }
    });
  return newRoutes;
}

console.log(routes);
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})

export class AppRoutingModule {
}

UPDATE #1

import { ApiResult } from './objects/api';

import { DashboardComponent } from './dashboard/dashboard.component';

import { NgModule } from '@angular/core';
import { RouterModule, Routes, Router} from '@angular/router';

import { environment } from '../environments/environment';

const routes: Routes = [{path: 'cms/bla', component: DashboardComponent},
{path: 'bla', component : DashboardComponent},
{path: 'cms/dashboard', component : DashboardComponent}];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})

export class AppRoutingModule {
 constructor(router: Router) {
    fetch(environment.apiUrl + '/routes/').then((value: Response)  => {
    return value.json();
    }).then((routeResults: ApiResult) => {
    for (let i = 0; i < routeResults.data.length; i++) {
      router.config.unshift({path: routeResults.data[i]['path'], component: DashboardComponent});
      }
      console.log(router.config);
    });
 }
}

Answer №1

When you send an API request to retrieve routes, they are processed asynchronously. By the time the API response returns, you may have already displayed the routes with only one hardcoded.

To include your async routes in your AppComponent (or any other component), you can utilize "Router.config".

Simply follow these steps in your AppComponent constructor:

constructor(router: Router){
    fetch(environment.apiUrl + '/routes/').then((value: Response)  => {
    return value.json();
    }).then((routeResults: ApiResult) => {
    for (let i = 0; i < routeResults.data.length; i++) {
      this.router.config.unshift({path: routeResults.data[i]['path'], component: DashboardComponent});
      }
    });
}

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

Create a new FetchEvent instance within Jest specifically for a Cloudflare Worker deployment

The TypeScript template repository for Cloudflare Workers includes a test that mocks a GET request by instantiating the Request to simulate the input parameters for the handleRequest function. After some modifications to the template, I now pass the raw F ...

[webpack]: npm ERROR! Call stack size limitation exceeded

While trying to install webpack using npm i -D webpack, an error is encountered as shown below. npm ERR! Maximum call stack size exceeded npm ERR! A complete log of this run can be found in: npm ERR! /Users/shobhuiy1/.npm/_logs/2019-02-05T10_31_29_46 ...

I am interested in utilizing Sequelize, Vue, and Node to implement a query that filters data once it is retrieved to display on my view

Within my project, there's a table tracking user responses to a quiz. By utilizing the following query, I've successfully retrieved all the information from that table and stored it in my TotalQuizResponses array for display: this.totalQuizRespon ...

The process of AJAX polling a JSON-returning URL using jQuery's $.ajax() method does not appear to provide up-to-date responses

I am currently working on a project that involves polling a specific URL for a JSON response using AJAX. The initial AJAX request alerts the server of my need for JSON content, prompting it to start building and caching the response. Subsequent AJAX reques ...

Verify whether the element has been clicked prior to deletion

Here is the jquery code I'm working with: $(document).on('focusout', '#element_a', function(e){ $('#element_b').remove(); }); $(document).on('click', '#element_b', function(e){ // additional ...

Using TypeScript to utilize an enum that has been declared in a separate file

Imagine I have defined an enum in one file (test1.ts): export enum Colors{ red=1, blue=2, green=3 } Then in another file (test2.ts), I am creating a class with a method. One of the parameters for that method is a Color from the Colors enum: ...

Using Angular's ng-switch directive within a select dropdown option

Can we implement the [Data Presentation Format] to be utilized in the [Dropdown Box]? Specifically, I would like the "parent" items to appear as is within the dropdown, while the "child" items should have a [tab] indentation to denote their relationship wi ...

Error caused by CORS Policy blocking XMLHttpRequest access (Python/Angular)

I've encountered a troubling issue with my Angular application, currently live on the web. Users are unable to log in due to this issue, and those who are already logged in are experiencing issues while using the website. The error message reads: Acc ...

Can we create a process that automatically transforms any integer field into a hashed string?

Is there a non-hacky way to hash all IDs before returning to the user? I have explored the documentation extensively but haven't found a solution that covers all scenarios. I am working with Postgres and Prisma ORM, managing multiple models with rela ...

Failure to send Websocket connection

Currently working on PHP, here's a snippet: $room_array = array(); $room_array[0] = 'room-list'; $room_array['info'] = array('room_name' => $room['room_name'], 'owner' => $username['usernam ...

Designing a pop-up window for fetching data using AngularJS

I'm having trouble loading data into a modal window using AngularJS. I want the URL to change when a link is clicked and have the data load into a modal window instead of a new page. I attempted to use the jQuery Facebox plugin, but it doesn't s ...

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

Verify whether a string initiates with any of the strings contained in a specified array

Is there a way in JavaScript to determine if a string begins with any of the strings contained within an array? For instance, You have an array comprised of strings: const substrs = ['the', 'an', 'I']; And you also possess ...

The error message at line 757 in utils.ts states that the [div] element is not recognized as a valid <Route> component

I've been trying to set up routes for Register and Login components inside a div with the className 'container' using react-router v6. However, whenever I try to access these components, I end up on a blank page. Strangely, when I remove the ...

Removing the initial string before an object can be done by utilizing various techniques and

The response I am receiving is in the following format: javax.xml.rpc.ServiceException: [{"ReturnCode":0,"counter":"\\\\sap\\CTI \\CTIConnection"},{"ReturnCode":101,"ErrSt ...

I have developed an interactive image carousel that allows users to click on each image for further exploration

Whenever I try to add an event to the image, it appears to be getting blocked by something, causing my function not to execute. Here is my slider setup: <ion-slide-box slide-interval="4000" auto-play="false" does-continue="true" show-pager="true"> ...

Submitting data to a PHP script using AJAX and the $_POST method

I'm attempting to transfer data from my AJAX request into a PHP $_POST variable in order to update my database. HTML <form id="23" method="post"> <select name="admin" onchange="chosenadmin(23)"> <option value="rick">rick&l ...

JQuery .click Event doesn't center elements even with transform-origin adjustment

In the JSfiddle provided below, you can see that after a click event occurs, two span (block) elements rotate 45deg to form an "X". However, both elements are slightly shifted left, creating an off-center "X" relative to the parent's true center-origi ...

Alter the data displayed by the Radio button using Angular when the Submit button is clicked

I've encountered an issue where I need to alter a div based on the selection of a radio button. Currently, it changes instantly upon button click, rather than waiting for submission. My desired outcome is for the value to be submitted when the button ...

Function that sets object properties based on specified keys and verifies the value

Let's consider a scenario where we have an object structured like this: interface Test{ a: number; b: string; c: boolean; } const obj:Test = { a: 1, b: '1', c: true, } We aim to create a function that can modify the value ...