Building the Products Service
Our application would be nothing without the data. In this course part you will display products images, description and prices in your Angular application.
It's time to enable displaying products in your application. In this step, you are going to use product images that are available for download here. Place the images inside the src/assets/images folder in your project.
To generate the component and the service that you are going to implement, type the following commands in the terminal:
ng g s products --skipTests
ng g c product-details --skipTests
Products service#
Before digging into the service, let's declare the Product
interface that you will use across the application. Create a new file called product.model.ts in the src/model directory and copy the following code:
export interface Product {
id: string;
name: string;
description: string;
price: number;
image: string;
}
To implement ProductsService
, add the following code to src/products.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Product } from '../model/product.model';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class ProductsService {
private API_URL = '/api';
constructor(private httpClient: HttpClient) {}
public getProducts(): Observable<Product[]> {
return this.httpClient.get<Product[]>(
`${this.API_URL}/products`
);
}
public getProduct(
productId: string
): Observable<Product> {
return this.httpClient.get<Product>(
`${this.API_URL}/products/${productId}`
);
}
}
ProductsService
is consuming two API endpoints:
GET /products that returns the list of all products (without product descriptions).
GET /products/:id that returns the full description of the product specified by the
:id
query parameter.
Notice that you've assigned the value /api
to the API_URL
constant. From now on, you are going to run your frontend together with the backend. You don't need to specify the whole URL of the API anymore because it will be served from the same domain as the frontend. Apply the same modification in src/app/user.service.ts and change API_URL
accordingly.
Product details component#
You now need to add ProductDetailsComponent
to the application routing. Change routes in src/app-routing.module.ts to the following:
import { ProductDetailsComponent } from './product-details/product-details.component';
const routes: Routes = [
{ path: '', redirectTo: 'products', pathMatch: 'full' },
{ path: 'products', component: ProductsListComponent },
{
path: 'product/:id',
component: ProductDetailsComponent,
},
{ path: 'login', component: LoginComponent },
{
path: 'favorites',
component: FavoritesComponent,
canActivate: [AuthGuardService],
},
];
This page is a preview of The newline Guide to Angular Universal