Angular 15 How to load data before rendering the component?

This tutorial talks about how to load data before rendering a component

This post includes load data from API before the component is rendered.

There are multiple ways we can load API data before the component is rendered.

  • One-way call API and promise in Constructor.
  • Second way, use resolve data
  • Finally, Activate Route

In this post, We are going to discuss the first approach

How to load API data before rendering the component

Let’s create an angular service that pulls data from API or database.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from "rxjs/operators";
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private employee_api_url: string = 'api.localhost.com';

  constructor(private httpClient: HttpClient) { }


  getEmployees(): Observable<any> {
    return this.httpClient.get(this.employee_api_url + '/read')
      .pipe(map((resp: any) => resp.json()),
        catchError(error => this.throwError(error))
      )

  }


  throwError(error: any) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}

In the Angular Component, Inject Angular Service for the constructor

And also declare a variable isLoaded with false initially

import { Component } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [EmployeeService]
})
export class AppComponent {
  title = '';
  emps: [] = [];
  isLoaded:boolean=false;
  constructor(private employeeService: EmployeeService) { }

  ngOnInit() {



  }

Write a method that returns Employee. Once the API is ready, set the isLoaded value to true


  getEmployees(): Promise<Employee>{

          this.employeeService.getEmployees().subscribe((data) => {
      this.emps = data;
      this.isLoaded=true;
    }, (error) => {
      console.log("An error accessing Employee Service");
    })

  }
}

In html template, use ngIf with isLoaded to load any component or data after API returns the data.

<div *ngIf="isLoaded">Load data before component example</div>