Exploring the world of dynamic routing in Angular using JSON data

I am facing an important query. Can we implement async routing in Angular 10? I have come across AsyncRoute in Angular2, but it seems to no longer exist in Angular 10.

Here is a snippet of my code :

 getRoutes() {
   return this.http.get(this.APIROOT + 'routes');
 }

pageService.getRoutes().subscribe( (pageRoutes:RouteInterface[]) => {
     const componentMap = {
       'PageComponent': PageComponent,
       'BlogComponent':BlogComponent
     };
     for(let route of pageRoutes){
       this.routes.push({ 'path' : route.route, 'component' : componentMap[route.component]})
     }
   }) 

While this generates a valid and correct Route Array, my issue lies in the fact that this data is asynchronous. Therefore, I cannot directly push the data to the route:Routes Array in app-routing.module.ts using the constructor. Is there another method to accomplish this task? Has anyone encountered similar challenges before?

Answer №1

It seems like there may not be any responses to this question. I will take it upon myself to provide an answer. After encountering a problem, I managed to find a solution on my own. Although I am unsure of the language used for your API, I personally utilized Python (specifically Django DRF + Wagtail) and implemented a signal hook on post_save. This allows me to save all Page Model Objects into a JSON file every time a page is saved. The JSON file is then stored within the Angular Project Directory. By extracting content from this file, I can dynamically create routes using this method.

Below is the code snippet from my AppComponent:

export class AppComponent implements AfterViewChecked {
  routes: RouteInterface[] = routes;
  routeArr: Routes = [

  ];
  constructor(private router: Router) {
    const componentMap = {
      'PageComponent': PageComponent,
      'BlogComponent': BlogComponent
    };
    for (let route of this.routes) {
      this.routeArr.push({ 'path' : route.route, 'component' : componentMap[route.component]})
    }
    console.log(this.routeArr)
    this.router.resetConfig(this.routeArr)
  }

  ngAfterViewChecked() {
    this.router.resetConfig(this.routeArr)
  }

}

This thread can now be considered closed.

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

Ways to assign a default value to a radio button using a mock JSON dataset

As a beginner in AngularJS2, I am looking to resolve an issue where the checkbox is automatically checked when retrieving values from a mock JSON file. Can someone please help me? <div class="form-row"> <div class="formHeading">Skills *< ...

The issue with npm modules not appearing in EMCA2015 JS imports persists

I am currently in the process of developing a mobile application with Nativescript using the Microsoft Azure SDK. To get started, I installed the SDK via npm by running this command: $ npm install azure-mobile-apps-client --save However, upon attempting ...

tsconfig issues with compilation and testing

Here is the configuration in my tsconfig.json { "compilerOptions": { "noImplicitAny": true, "declaration": false, "strict": true, "strictNullChecks": false, "target": "E ...

Implement a sub-routine in Office.js Javascript Word add-in that utilizes asynchronous execution context

Lately, I've been exploring the world of developing an Office.js add-in for Word and have found some success. One task that seems to come up frequently in my add-in is searching and replacing text, which needs to be performed by various action buttons ...

Overlap with upper picture formatting

I've been struggling to create an ion-card with two images: a main picture and a small book cover. Any ideas on how to achieve this? Note: The layout should have 2 images, one at the top and another as a small book cover. Check out this sample on St ...

Trigger Screen Reader to Announce When a Component Is Deleted

When the last filter item is removed, I want the screen reader to announce "All Filters Are Removed." However, if the active filter component is removed without any other element to assign an aria-label attribute, I'm not sure how to handle this situa ...

Unable to configure Angular 2 tour of champions tutorial

When I accessed the Hero Editor page (https://angular.io/docs/ts/latest/tutorial/toh-pt1.html), I followed the given instructions: “Follow the setup instructions for creating a new project named angular-tour-of-heroes, after which the file structure sho ...

Displaying data from multiple checkboxes in an Angular application using an array

I'm currently facing an issue with displaying checked data in an Array within my Angular application. Upon clicking the checkbox, I receive a true value, but unfortunately, the data does not display as it contains null values. For reference, here is ...

Can undefined be forcibly assigned with strict null checks enabled?

Considering enabling the strictNullChecks flag for a TypeScript project I've been developing leads to numerous compiler errors. While some of these errors are relevant edge cases, many follow a specific pattern. type BusinessObject = { id: string; ...

Troubleshooting import errors with Typescript for C3 and D3 libraries

I have recently started working on a project using the C3 graphing library within an Ionic2/Angular2 TypeScript setup. After installing C3 via npm and the type definitions via tsd, I imported it into my own TypeScript file like this: import {Component} fr ...

Is there a way for me to navigate from one child view to another by clicking on [routerLink]?

Currently, I am facing an issue with switching views on my Angular website. The problem arises when I attempt to navigate from one child view to another within the application. Clicking on a button with the routerlink successfully takes me to the new view, ...

What is the technique for passing a value from parent to child components in React?

Here is a plunker demonstration that I have set up: https://plnkr.co/edit/5XbuxoGG6NqomayLP4Ae?p=preview Below is the code snippet: > @Component({ selector: 'my-app', template: ` > <layout [child]="childModal"> > &l ...

What is the best way to configure eslint or implement tslint and prettier for typescript?

In my React/Redux project, I recently started integrating TypeScript into my workflow. The eslint configuration for the project is set up to extend the airbnb eslint configurations. Here's a snippet of my current eslint setup: module.exports = { // ...

Using the parameter of type 'never' is necessary as per the TypeScript error message, which states that the argument of type 'string' cannot be assigned to it. This error persists even when

https://i.sstatic.net/tkX07.png const index = selectedActivities.value.indexOf(activity_id); I encountered a TypeScript error saying 'Argument of type 'string' is not assignable to parameter of type 'never'. How can I fix this iss ...

Angular route permissions and safety

Exploring the world of Angular has introduced me to its intricate routing mechanics and the use of routing guards for authorization on different routes. However, I can't help but feel like this guard mechanic may not be enough to fully secure my web s ...

How can I retrieve the row index in an Angular Mat-Table that has expandable content?

Having a mat-table with expandable content on a page, I am seeking a solution to record the row number of the table when clicked. While I successfully achieved this with a regular table in the HTML file using: <tr mat-row *matRowDef="let row; columns: ...

What's causing the "* before initialization" error in Vue with TypeScript?

I am encountering an issue with my code where I get the error "Cannot access 'AuthCallback' before initialization" when attempting to call the router function in the AuthCallback component. What could be causing this problem? The desired function ...

Checking Validity of an Array of URLs with Class-Validator

I'm utilizing Class-Validator for validating DTO properties in my Nest.js application. One of the properties is "images", which is an array of strings representing URLs. I need to validate each URL in this array. class SomeDto { // ... // Arr ...

`Is it necessary to utilize @Inject in Angular 2?`

When needing to use a service that I have created, I make use of the @Inject decorator: export class ScheduleComponent { constructor(@Inject(ConnectionsApi) private connectionsApi: ConnectionsApi ) { } } However, when working with a service provided ...

Troubleshooting: Unable to locate .vue.d.ts file during declaration generation with Vue, webpack, and TypeScript

Currently, I am developing a library using Typescript and VueJS with webpack for handling the build process. One of the challenges I'm facing is related to the generation of TypeScript declaration files (.d.ts). In my source code, I have Typescript ...