Angular is a popular open-source JavaScript framework for building dynamic and sophisticated web applications. It is developed and maintained by Google and is designed to simplify the development process by providing a structured framework for building single-page applications (SPAs) and web applications in general.
ngular provides a robust set of tools and features that allow developers to efficiently create complex user interfaces, handle data binding, manage components, handle routing, work with forms, interact with APIs, and more. It follows the Model-View-Controller (MVC) architecture, which helps in organizing code and separating concerns.
Step 1. Set up a new Angular project
First, make sure you have Node.js and Angular CLI installed. If not, you can install Angular CLI using npm (Node Package Manager) with the following command.
npm install -g @angular/cli
Now, create a new Angular project.
ng new angular-First-Api-Integration
Step 2. Create a service to fetch data from the API
In this step, we'll create a service that will handle the API requests. Run the following command to generate a new service.
ng generate service product
Open the generated service file product.service.ts and modify it to use the provided API URL.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ProductService {
private apiUrl = 'https://dummyjson.com/products';
constructor(private http: HttpClient) { }
getProducts(): Observable<any> {
return this.http.get(this.apiUrl);
}
}
Step 3. Use the service in a component
Generate a new component for displaying the list of products.
ng generate component product-list
Open the generated component file product-list.component.ts and modify it to use the ProductService to fetch and store the list of products.
import { Component, OnInit } from '@angular/core';
import { ProductService } from '../product.service';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
products: any = [];
constructor(private productService: ProductService) { }
ngOnInit(): void {
this.productService.getProducts().subscribe(data => {
this.products = data;
});
}
}
Step 4. Display the data in the component's template
Open the product-list.component.html file and modify it to display the list of products.
<ul>
<li *ngFor="let product of products">
{{ product.name }} - {{ product.price | currency }}
</li>
</ul>
This template will display the list of product names and prices fetched from the provided API.
Step 5. Add the component to the app
Finally, add the ProductListComponent to the main app component (app.component.html).
<app-product-list></app-product-list>