What is the best way to utilize resolve and promises in Angular2 to ensure that data is loaded from the server before rendering a page in the

I am currently developing an Angular 6 application with the requirement to load dynamic routes from a database. To achieve this, I have created a service class called DynamicRoutingService which is responsible for loading both static and dynamic routes from the database and adding them in app.module.ts --> RouterModule.forRoot(RouteCollection).

Within the DynamicRoutingService class, I am retrieving data using the subscribe method. However, my issue arises when the page of the requested URL is rendered before the subscribe method receives the HTTP result, causing the application to throw an error of an invalid route.

I have attempted to use resolve and promises to address this issue but I am unsure of how exactly to implement it. This is where I need assistance.

App Route Resolver

@Injectable()
export class AppRoutingResolver implements Resolve<any>{

constructor(
    private router: Router
){}

resolve(route: ActivatedRouteSnapshot): Promise<any> | boolean{
    return false;
 }
}

App.Component

export class AppComponent {

constructor(private routingService: DynamicRoutingService){
   routingService.initializeDynamicRoutes(); // call service to reload routes
}
}

App.Routing.Module

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

 constructor(
 private router: Router
 ) { 
 }
}

DynamicRoutingService

@Injectable({
 providedIn: 'root'
 })

 export class DynamicRoutingService {

private dynamicRoutes: Route[] = [];
private waitToLoadRoutes: boolean = true;
private dynamicRoutesData: any;
private routeObject: any;
routeSubject: string = "survey";
static forEach: any;

constructor(
    private router: Router,
    private dynamicRoutesDataServices: DynamicRoutesDataServices
 ) { }

 public initializeDynamicRoutes() {
    this.loadDynamicRoutes();
 }


public loadDynamicRoutes(): Route[] {
    //LOADING DATA FROM DATABASE

this.dynamicRoutesDataServices.GetDynamicRoutesCollection(this.routeSubject)
        .subscribe((result: any) => {
            if (result) {
                this.dynamicRoutesData = result
                if (this.dynamicRoutesData) {
                    this.assembleDynamicRoutes();
                }
            }
        });

    return this.dynamicRoutes;
}

Data Service to Call HTTP Query

export class DynamicRoutesDataServices{

constructor(
    private getDynamicRoutesQuery: GetDynamicRoutesQuery
){}

public GetDynamicRoutesCollection(routesSubject: string): any{
    this.getDynamicRoutesQuery.initialise(routesSubject);
    var result = this.getDynamicRoutesQuery.execute();
    return result;
 }
}

HTTP Query to Call API

@Injectable()
export class GetDynamicRoutesQuery extends BaseQuery<any> 
{

private data: any;

public initialise(dynamicRouteSubject: string): void{
    this.method = RequestMethod.Post;

    if(dynamicRouteSubject){
         this.data = {
            RouteSubject: dynamicRouteSubject
        }
    }

    this.setBody(this.data);

    super.setEndPoint(`myside/GetDynamicRoutes`);
  } 
}

Answer №1

It is important to consider the appropriate approach for loading dynamic routes in Angular. Resolvers serve as helpers that pre-fetch data for a specific route.

For example:

 RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamComponent,
        resolve: {
          team: TeamResolver
        }
      }
    ])

The resolver will store information about the team in the team property within the ActivatedRoute data property. Therefore, it should be attached to an existing route.

https://angular.io/api/router/Resolve

https://codeburst.io/understanding-resolvers-in-angular-736e9db71267

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

Height and placeholder issue with ion-searchbar

Hey there, I hope everything is going well for you. I've encountered a problem with the Ionic 5 - Angular Searchbar feature. This is how I added the searchbar: <ion-searchbar [(ngModel)]="text" (ionChange)="sear ...

Utilize Ant Design TreeSelect to seamlessly integrate API data into its title and value parameters

I am currently working on populating a Tree Select component in ANT Design with data fetched from an API. The response from the API follows this structure: projectData = ProjectData[]; export type ProjectData = { key?: number; projectId: number; ...

Tips for eliminating duplicate entries in ag grid using Angular

Is there a way to eliminate the recurring assetCode entries in ag grid? The PRN and PRN1 values seem to be repeating unnecessarily. Check out the code below: list.component.ts ngOnInit() { this.rowData.push( { 'code': 'Machi ...

Having trouble with GoogleSignIn in React Native Firebase app

During the development of my React Native App, I integrated Firebase as the Authentication System. The app compiled successfully, but upon attempting to use the GoogleSignIn method, an error message appeared on the AndroidToast: "Se ha producido un error. ...

Adding a custom class to an ng-bootstrap tooltip can be accomplished by utilizing Angular's

Having trouble customizing an ng-bootstrap tooltip with a custom class. Markup: <i class="fa fa-info-circle" aria-hidden="true" [ngbTooltip]="infoTooltipTemplate" [tooltipClass]="info-tooltip" placement="top"></i> Stylesheet: .info-tooltip ...

Ways to broaden the type signature of a Typescript comparator in order to facilitate sorting by properties nested within objects?

Here is a function that I created: arr.sort(alphabeticallyBy("name")) The function has the following signature: <T extends string>(prop: T) => (a: Partial<Record<T, string>>, b: Partial<Record<T, string>>) => ...

Enhancing Test Components with Providers in "React Testing Library": A Step-by-Step Guide

I am currently working with React-Testing-Library and have set up my main.tsx file with Redux-Toolkit and React-Router wrappers like this: ReactDOM.createRoot(document.getElementById("root")!).render( <React.StrictMode> <Provider s ...

Hide Angular Material menu when interacting with custom backdrop

One issue I am facing is with the menu on my website that creates a backdrop covering the entire site. While the menu can be closed by clicking anywhere outside of it, this functionality works well. The problem arises when users access the site on mobile ...

I have implemented an email validation form in Angular, however, if the validation is not properly handled, the data will still be stored. How

When I enter an email address, for example: if I enter "abc" it shows an alert saying "please enter a valid email". If I leave it blank and try to submit, it shows an alert saying "email required". But when I click register, the data is saved regardless of ...

Experiencing problems with the Locale setting when utilizing the formatNumber function in Angular's core functionalities

I am having trouble formatting a number in Angular using the formatNumber function from the Angular documentation. Here is my code snippet: import {formatNumber} from '@angular/common'; var testNumber = 123456.23; var x = formatNumber(Numb ...

Issue with Angular 5 EventEmitter causing child to parent component emission to result in undefined output

I've been trying to pass a string from a child component to its parent component. Child Component: //imports... @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.c ...

Angular 6 introduces a new component with cascading comboboxes for easier data organization

In my Angular 6 project, I have successfully implemented a shared component called country-state. It is functioning perfectly. VIEW MY PERFECT WORKING EXAMPLE However, upon dividing the country-state component into separate country and state components, ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...

Create a series of buttons in Angular 2 that are linked to components with a click event

I am facing an issue with a component that generates a list of buttons, where I want to connect the click event to show a child component. The problem is that my current implementation using a local variable causes all buttons to display the last child com ...

A guide on implementing getStaticProps using TypeScript in Next.js

Why am I consistently receiving undefined results when attempting to retrieve all posts from my backend? What could be causing this issue? import { AppContext } from '@/helpers/Helpers' import axios from 'axios' import { GetStaticProps} ...

Angular causing issues with Perfect Scrollbar functionality

In an attempt to enhance the scrollbar in my Angular application, I integrated the following library: https://github.com/zefoy/ngx-perfect-scrollbar Following the guidelines provided in the documentation from the link, I included imports into my app.modul ...

IDE type inferences are wrong for the Polymorphic React component

declare const MyComponent = <A extends {id: bigint|number}>(props: MyProps<A>) => React.FC<{}> interface MyProps<A extends {id: number}> { data: A[] orderBy: keyof A } declare const x: { id: number, foo: string }[] const F ...

Having trouble implementing catchError in a unit test for an HttpInterceptor in Angular 11

I am facing challenges in completing a unit test for my HttpInterceptor. The interceptor serves as a global error handler and is set to trigger on catchError(httpResponseError). While the interceptor functions perfectly fine on my website, I am struggling ...

Integrating Spartacus: Unresolved peer dependencies detected in package installation

Just set up a fresh project using the latest Angular CLI 13.3.6 (node 16.15.0, yarn 1.22.15). I'm attempting to incorporate Spartacus as detailed in this guide: but when I execute ng add @spartacus/schematics@latest I encounter the following error: ...

Is TypeScript's Structural Typing the exception to the rule?

Let me illustrate two scenarios where I encountered difficulties. The first example involves two points: one in 2d and one in 3d: type Point2D = { x: number, y: number }; type Point3D = { x: number, y: number, z: number }; let point2D: Point2D = { x: 10, ...