One of the most common asynchronous processes are data requests from an API. For this, Angular has its own HTTP client intended to serve the purpose called HttpClientModule
.
API consumption with Angular
Step 1: Start by importing the HttpClientModule
module, in the main module of your application from @angular/common/http
.
import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ ], imports: [ HttpClientModule ], providers: [], bootstrap: [ ] })export class AppModule { }
Step 2: Create a service to make all the API calls you need. In this service you have to import the Angular HTTP client and create a method for each endpoint for which you need to make a request.
import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root'})export class ApiService { constructor( private http: HttpClient, ) { } getProducts() { return this.http.get(`https://example.com/api/productos`); } } }
Step 3: Import this new service into your components to perform the API calls.
import { ApiService } from 'src/app/services/api.service'; @Component({ selector: 'app-catalogo', templateUrl: './catalogo.component.html', styleUrls: ['./catalogo.component.scss'] })export class CatalogoComponent implements OnInit { public products: Product[] = []; constructor( private apiService: ApiService ) { } ngOnInit(): void { this.apiService.getProducts() .subscribe(res => { this.products = res; }); } }
The ngOnInInit()
method is the appropriate place for asynchronous calls, remember that it is not good practice to do it in the constructor.
The entire Angular HTTP client is based on Observables, so it is advisable to subscribe to the service method to get the data when the API responds.
TIP: You don't need to do an .unsubscribe() after the API call. Angular already does that for you, when you use its HTTP client.
Playing with observables
If you don't have a Rest API at your disposal that returns data for your application, I'm going to show you a little trick so that you can still continue your development with a data mock.
A Mock is a simulation of the real data that the API will return, except this time you will get the data from the service through an Observable.
import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root'})export class ApiService { constructor() { } getProducts(): Observable<Product[]> { return of([ { id: 1, name: 'Toy car', price: 100, image: 'https://static3.depositphotos.com/1000865/118/i/600/depositphotos_1183767-stock-photo-toy-car.jpg' }, { id: 2, name: 'Rag doll', price: 180, image: 'https://kinuma.com/8869-home_default/muneca-de-trapo-mali.jpg'}, { id: 3, name: 'Soccer ball', price: 120, image: 'https://media.istockphoto.com/photos/soccer-ball-isolated-3d-rendering-picture-id1257575611?k=20&m=1257575611&s=612x612&w=0&h=g530fFJspT42xFGY7HycLvpBKLXpJ2XAkKCRyY-SK80=' }, { id: 4, name: 'Castle', price: 220, image: 'https://i.imgur.com/44nzvkQ.jpg' } ]) } } } } }
In the above example, from RxJS you are importing "Observable" and "of" which will help you to prepare your data.
With Observable you can type the response of your methods as follows Observable<Product[]>
to indicate that it will return an observable with an array of products. The of
function converts whatever you put inside it (an object, an array, a number, etc), into an observable.
This way, without having a real API, you can simulate the interaction of your component with data coming from an asynchronous process.
View project source code
Contribution created with contributions from Kevin Fiorentino.
Want to see more contributions, questions and answers from the community?