Hello to all, welcome to therichpost.com. In this post, I will tell you, How to send calls in Angular 9 to an API?
Post Working:
In this post, I will show you multiple API Calls using Angular 9 HTTP POST and HTTP GET services.
Here are all the API calls and please learn and use them carefully:
1. Simple API call using Angular 9 HTTP GET and you can use into your app.component.ts file or any service file:
... import { HttpClient } from '@angular/common/http'; ... data = []; //Declare variable to store API data constructor(private http: HttpClient) { //Basic Get API call this.http.get('http://localhost/mypage.php').subscribe(data => { //Pushing API data to declare variable this.data.push(data); }, error => console.error(error)); }
2. API Call using Angular 9 HTTP Post service. You can send data with this service like Form Post Data and you can add this code into your app.component.ts file or any service file:
... import { HttpClient } from '@angular/common/http'; ... constructor(private http: HttpClient) {} ... // Looks like Form Submit Function onSubmit() { // creates an empty FormData object var myFormData = new FormData(); // Begin assigning parameters myFormData.append('name', this.registerForm.value.name); myFormData.append('email', this.registerForm.value.email); myFormData.append('phone', this.registerForm.value.phone); // POST API With DATA return this.http.post('http://localhost/mypage.php/' , myFormData).subscribe((res: Response) => { //Getting API Response }); } ...
3. Multiple API Calls in one time using Angular 9 POST GET forkJoin and you can add this code into your app.component.ts file or any service file:
forkJoin seems merging API requests(array merging)
... import { HttpClient } from '@angular/common/http'; import {forkJoin} from 'rxjs'; ... ... data = []; // Declare array variable constructor(private http: HttpClient) {} ... ... //Something like Form Submission FormSubmit() { //creates an empty FormData object var myFormData = new FormData(); myFormData.append('id', id); //Call Multiple API Using forkJoin forkJoin(this.http.post('http://localhost/mypage.php', myFormData), this.http.get('http://localhost/mypage.php')) .subscribe(([call1Response, call2Response]) => { //Pushing API data to array variable this.data.push(call2Response); }); } ...
If you have any kind of query regarding Angular 9 API calls then you can comment below.
Jassa
Thank you
Hi,
This is a very nice post, but can you have not mentioned the file name before every code. it makes us confuse where we need to write the code . Please mentioned the file name (like component/service.ts) so that help to understand this
Hi, thank you for comment.
You can write above code into your app.component.ts file.