{

Angular 13 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 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 about first approach

How to load API data before rendering the component.

Let’s create an angular service which 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 Angular Component, Inject Angular Service for constructor

And also declare an 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 which return Employee. Once the API is ready, set 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>
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.