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.
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.
In this post, We are going to discuss about first approach
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>
🧮 Tags
Recent posts
Multiple ways to iterate a loop with index and element in array in swift How to reload a page/component in Angular? How to populate enum object data in a dropdown in angular| Angular material dropdown example How to get the current date and time in local and UTC in Rust example Angular 13 UpperCase pipe tutorial | How to Convert a String to Uppercase exampleRelated posts