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 the component is rendered.
In this post, We are going to discuss the first approach
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>
🧮 Tags
Recent posts
Ways to skip test case execution in Gradle project build Learn Gradle | tutorials, and examples How to run only single test cases with Gradle build How to print dependency tree graph in Gradle projects How to perform git tasks with build script?Related posts