Selanjutnya, kita buat frontend menggunakan Angular yang akan berkomunikasi dengan API yang sudah dibuat.
-
Buat project Angular baru:
ng new my-angular-app --routing --style=css
Pilih
Yes
untuk Angular routing.
-
Masuk ke folder project:
cd my-angular-app
-
Buat service untuk mengakses API:
Jalankan:
ng generate service services/product
Kemudian edit
src/app/services/product.service.ts
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Product {
id: number;
name: string;
price: number;
}
@Injectable({
providedIn: 'root'
})
export class ProductService {
private apiUrl = 'https://localhost:5001/api/products';
constructor(private http: HttpClient) {}
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.apiUrl);
}
getProduct(id: number): Observable<Product> {
return this.http.get<Product>(`${this.apiUrl}/${id}`);
}
addProduct(product: Product): Observable<Product> {
return this.http.post<Product>(this.apiUrl, product);
}
updateProduct(id: number, product: Product): Observable<void> {
return this.http.put<void>(`${this.apiUrl}/${id}`, product);
}
deleteProduct(id: number): Observable<void> {
return this.http.delete<void>(`${this.apiUrl}/${id}`);
}
}
-
Tambahkan HttpClientModule di
app.module.ts
:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [ ... ],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
-
Buat komponen untuk menampilkan daftar produk:
Jalankan:
ng generate component components/product-list
Edit
src/app/components/product-list/product-list.component.ts
:
import { Component, OnInit } from '@angular/core';
import { ProductService, Product } from '../../services/product.service';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
products: Product[] = [];
loading = true;
error = '';
constructor(private productService: ProductService) {}
ngOnInit(): void {
this.productService.getProducts().subscribe({
next: (data) => {
this.products = data;
this.loading = false;
},
error: (err) => {
this.error = 'Gagal memuat data produk.';
this.loading = false;
}
});
}
}
Dan buat tampilan di
product-list.component.html
:
<div class="p-4">
<h3 class="text-2xl font-semibold mb-4 text-indigo-700">Daftar Produk</h3>
<div *ngIf="loading" class="text-indigo-500">Memuat data...</div>
<div *ngIf="error" class="text-red-600">{{ error }}</div>
<ul *ngIf="!loading && !error" class="space-y-3">
<li *ngFor="let product of products" class="border rounded p-3 bg-white shadow-sm hover:shadow-md transition">
<h4 class="font-bold text-lg">{{ product.name }}</h4>
<p>Harga: Rp {{ product.price | number }}</p>
</li>
</ul>
</div>
-
Jalankan aplikasi Angular:
ng serve
Buka
http://localhost:4200
di browser.