Patience is key as we anticipate the parent component/module loading the data

Just a note: I am aware of the existence of APP_INITIALIZER, but it appears to only work in the top-level module (app.module.ts) of the application.

I have a parent component that loads some data:

In admin-area.component.ts:

ngOnInit(): void {

  forkJoin([
    this._userService.getMe(),
    this._placeService.getAll()
    ])
    .pipe(finalize(() => this.afterInit()))
    .subscribe(
      ([user, businesses]) => {
        this._appState.user = user;
        this._appState.businesses = businesses;
        this.afterInit();
      }
    );
}

The issue arises with child components relying on this._appState.user and this._appState.businesses.

Loading this with APP_INITIALIZER isn't possible as the above data is only loaded when the user is logged in. The "logged-in" area is within a lazy-loaded module of its own.

So, the question here is simple:

How can I ensure that my data is loaded before child components attempt to display themselves?

This approach:

providers: [
  AdminAreaState,
  { provide: APP_INITIALIZER, useFactory: adminAreaInit, deps: [AdminAreaState], multi: true}
]

Hasn't been successful. adminAreaInit() isn't being called. It seems like APP_INITIALIZER only works for the main module app.module.ts. Is that correct?

What other options do I have?


I believe more details are necessary.

Note that I'm attempting to utilize *ngIf:

<div *ngIf="!business?.servicePlan">
  Please Upgrade
</div>

However, the problem occurs when I navigate to this page and refresh the page, where business is always undefined. It's a result of finding the right business in the Array of businesses using the businessId.

At the time the child component gets loaded, additional data is fetched. In this case, some reviews (comments).

Now, loadPage() fetches one page of the requested data for a business. _appState is supposed to be loaded first. If I try this:

  private loadPage() {
    console.log(this._appState);
    console.log(this._appState.businesses);
    this._appState.businesses.forEach(
      (b) => {
        console.log(b);
      });
    setTimeout(() => this._appState.businesses.forEach(
      (b) => {
        console.log(b);
      }
    ), 100);

    const businessId = this._appState.businessId;
    this.business = this._appState.businesses.find(b => b.id === businessId);
  }

This is what I get:

https://i.sstatic.net/P8t1t.png

As shown, this._appState contains businesses, but this._appState.businesses prints an empty array.

_appState.businesses is just an Observable:

ApplicationState service:

@Injectable()
export class ApplicationState {

  public businessIdChange;

  public businessesChange;

  private _user = new BehaviorSubject<UserModel>(null);

  private _businessId = new BehaviorSubject<number>(null);

  private _businesses = new BehaviorSubject<Array<BusinessModel>>([]);

  constructor() {
    this.businessIdChange = this._businessId.asObservable();
    this.businessesChange = this._businesses.asObservable();
  }

  set user(value: UserModel) {
    this._user.next(value);
  }

  get user(): UserModel {
    return this._user.getValue();
  }

  set businessId(businessId: number) {

    if (businessId === this.businessId) {
      return;
    }

    this._businessId.next(businessId);
  }

  get businessId() {
    return this._businessId.getValue();
  }

  set businesses(value) {
    this._businesses.next(value);
  }

  get businesses(): Array<BusinessModel> {
    return this._businesses.getValue();
  }

}

I'm unsure why this is happening and I thought pre-loading the data would make sense anyway. Could there be another underlying issue here?

Answer №1

Implement Angular Resolvers at the component level for efficient data loading. For additional details, you can refer to this resource.

Answer №2

If you are displaying child components through routing, utilizing resolvers could be a beneficial choice. An example of how to do this can be found in the documentation

When the parent component is directly calling the child component using the child component tag, employing *ngIf would be a suitable option - like this:

<child-component *ngIf="condition"></child-component>

Another alternative would be to utilize ngOnInit to initialize data within the child component.

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

Exploring the Pristine State of Nested Controls in Angular Reactive Forms

I'm currently in the process of putting together a nested form that's relatively simple. Form Group > Form Array > Form Group > Controls Within the HTML, I am attempting to include a Remove button that will only display when the last i ...

The functionality to close a Mat dialog is not functioning properly on Angular 11 with Material 11

I am trying to close the dialog by calling the close function of MatDialogRef instance, but unfortunately it is not working as expected. Within my ShareModule, there are components like HeaderCompose and LoginComponent. The HeaderComponent utilizes the Lo ...

Adjusting the focal point of a brochure on open street map

I am currently working on initializing a map in an Angular application using leaflet with openstreetmaps. I have set the center of the map so that it is displayed to the user when they open the site. However, I am now trying to figure out how to dynamica ...

ASP.NET 5 controller's action not binding correctly with Angular2 Http post request

When sending a post request from Angular2 to an ASP.NET 5 controller action, although the data is being posted correctly and the controller action is being reached, the parameters defined in the controller action are not being properly mapped as they are s ...

Exploring the power of Angular 10 components

Angular version 10 has left me feeling bewildered. Let's explore a few scenarios: Scenario 1: If I create AComponent.ts/html/css without an A.module.ts, should I declare and export it in app.module.ts? Can another module 'B' use the 'A ...

Angular drag and drop feature for interacting with intersecting elements like rows and columns within a table

I am currently working on implementing two intersecting drag and drop functionalities using cdkDragDrop. Although I generally try to avoid using tables, I have created one in this case for the sake of easier explanation. Here is the link to StackBlitz: ht ...

Implementing conditional data binding in Angular with ngIf directive

I've been struggling to showcase recipes from a specific food category. I'm attempting to iterate through an array of recipes within a parent component. <div class="row"> <div class="col-xs-8" *ngIf="{{ recipe.category }} === mexican" ...

The React component continuously refreshes whenever the screen is resized or a different tab is opened

I've encountered a bizarre issue on my portfolio site where a diagonal circle is generated every few seconds. The problem arises when I minimize the window or switch tabs, and upon returning, multiple circles populate the screen simultaneously. This b ...

Guide on setting up an AWS code pipeline for Elastic Beanstalk deployment on ASP.NET Core 5.0 with Angular

I am facing a challenge with deploying my ASP.NET Core 5.0 application with Angular to the EBS Windows environment using AWS CodePipeline (CI / CD). Despite searching various internet resources for solutions, I have not been able to find much help. My att ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

What's the best way to implement satisfies with a generic type?

In my development process, I am working with components that have default values combined with props. To streamline this process, I created a single function for all components: export function getAssignProps <T extends {}>(propsMass:T[]){ return ...

Tips for concealing routes in the address bar on Angular versions 5 and above

Is it possible to conceal routes from the browser's address bar? Example: http://localhost:4200/user/profile to http://localhost:4200 Is there a way to hide routes? ...

How can I iterate through a variable in TypeScript?

initialize() { var elements = []; for (let i = 1; i <= 4; i++) { let node = { name: `Node ${i}` }; elements.push({ [`node${i}`]: node }); if (i < 4) { let edge = { source: `node${i}`, target: ...

What is the best way to refresh or reload a child component in Angular?

I have a transaction.component.html file that displays the app-deal-partners component. Every time the delete function is triggered, I want to refresh and reload the child component, which is the app-deal-partners component. I need to reload <app-deal- ...

Eliminate duplicated partial objects within a nested array of objects in TypeScript/JavaScript

I'm dealing with a nested array of objects structured like this: const nestedArray = [ [{ id: 1 }, { id: 2 }, { id: 3 }], [{ id: 1 }, { id: 2 }], [{ id: 4 }, { id: 5 }, { id: 6 }], ] In the case where objects with id 1 and 2 are already grou ...

An issue occurred in NestJs where it was unable to access the property '__guards__' because it was undefined

Currently, I am in the process of incorporating a basic authentication system into my Nest project. After including the following line in my controller: @UseGuards(AuthGuard('local')) I encountered this error message: ERROR [ExceptionHandler] C ...

What is the best way to obtain a signed cookie in aws-sdk-js-v3?

I am looking to utilize signed cookies for accessing private content stored on S3 using CloudFront for CDN. I am struggling to identify the appropriate commands to generate signed cookies in aws-sdk-js-v3. According to the updated SDK documentation, it sh ...

"How can we trigger a re-render of a React component once a promise is fulfilled? Is there a way to prevent rendering until the

Having attempted to make updates to a functional component that interfaces with an azure-devops-ui/Filter, I've encountered a situation where I am utilizing the azure-devops-extension-sdk to handle async responses. This component is intended to be use ...

Issue encountered while attempting to install dependencies using Stackblitz

I recently attempted to add ng-select to my StackBlitz project by including it in the dependencies section and importing it in app.module.ts. However, I encountered an error. You can view my code here. import { NgModule } from "@angular/core"; import { Br ...

Unlock the Power of RxJS Observables in Angular

Issue: My goal is to navigate to the login page if firebase-auth does not have a user logged in, and to an alternate page if a user is already logged in. To achieve this, I plan to call a function within a constructor service. private checkLoginStatus() ...