0% found this document useful (0 votes)
52 views

Building A Web App With Angular Managing Data Servicesjson File HttpClient

The document discusses adding a shopping cart feature to an Angular application. It describes creating a cart service to manage the cart data and share it between components. It also covers using the HTTP client to retrieve shipping prices from a JSON file and display them.

Uploaded by

Souki Hatem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Building A Web App With Angular Managing Data Servicesjson File HttpClient

The document discusses adding a shopping cart feature to an Angular application. It describes creating a cart service to manage the cart data and share it between components. It also covers using the HTTP client to retrieve shipping prices from a JSON file and display them.

Uploaded by

Souki Hatem
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Practical Angular

©2020 OMRANI Mohamed Amine [mohamedamine.omrani@fst.utm.tn]


Introduction
Throughout this Tutorial, you’ll learn how to use Angular to build client-side web applications.

You’ll learn:

• How to use the Angular CLI for quickly creating a front-end project, generating components, pipes,
directives, and services, etc.

• How to add routing and navigation using the Angular router.

• How to build and submit forms, using reactive and template-based approaches.
Session 5
Building a Web App with Angular
Managing Data & Services
json File & HttpClient
Introduction
At the end of Session 4, the online store application has a product catalog with two views: a product list and
product details. Users can click on a product name from the list to see details in a new view, with a distinct URL
(route).

In this Session, you'll create the shopping cart. You'll:


● Update the product details page to include a "Buy" button, which adds the current product to a list of
products managed by a cart service.

● Add a cart component, which displays the items you added to your cart.

● Add a shipping component (livraison), which retrieves shipping prices for the items in the cart by using
Angular's HttpClient to retrieve shipping data from a .json file.
Angular Services

What are Services ?

Services are an integral part of Angular applications. In Angular, a service is an instance of a class that
can be made available to any part of your application using Angular's dependency injection system.

Services are the place where you share data between parts of your application. For the online store, the
cart service is where you store your cart data and methods.
Angular Services : create service

Create the shopping cart service


Let’s add a "Buy" button to the product details page. Also set up a cart service to store information about products in the
cart.
Define a cart service $ ng generate service

import { Injectable } from '@angular/core' ;

@Injectable ({
providedIn : 'root'
})
export class CartService {

constructor () {}

}
Angular Services: Define a cart service

In the CartService class, define an items property to store the list (array) of the current products in the cart.
src/app/cart.service.ts

export class CartService {


items = [];
}
Angular Services: Define a cart service
Define methods to add items to the cart, return cart items, and clear the cart items: src/app/cart.service.ts
export class CartService {
items = [];

addToCart(product) {
this.items.push(product);
}

getItems() {
return this.items;
}

clearCart() {
this.items = [];
return this.items;
}
}
Angular Services: Use the cart service
Use the cart service
Now, you'll update the product details component to use the cart service. You'll add a "Buy" button to the product details
view. When the "Buy" button is clicked, you'll use the cart service to add the current product to the cart.

Open product-details.component.ts. and Set up the component to be able to use the cart service.

import { Component, OnInit } from '@angular/core';


import { ActivatedRoute } from '@angular/router';

import { products } from '../products';


import { CartService } from '../cart.service'; //Import the cart service.

export class ProductDetailsComponent implements OnInit {


constructor(
private route: ActivatedRoute,
private cartService: CartService //Inject the cart service.
) { }
}
Angular Services: Use the cart service
Define the addToCart() method, which adds the current product to the cart.

The addToCart() method:


● Receives the current product
● Uses the cart service's #addToCart() method to add the product to the cart
● Displays a message that the product has been added to the cart

export class ProductDetailsComponent implements OnInit {


addToCart (product) {
window .alert('Your product has been added to the cart!' );
this.cartService .addToCart(product);
}
}
Angular Services: Use the cart service
Update the product details template to have a "Buy" button that adds the current product to the cart.
src/app/product-details/product-details.component.html

<h2>Product Details </h2>

<div *ngIf="product">
<h3>{{ product.name }} </h3>
<h4>{{ product.price | currency }} </h4>
<p>{{ product.description }} </p>

<button (click)="addToCart(product)" >Buy</button>


</div>
Angular Services: Create the cart page
At this point, users can put items in the cart by clicking "Buy", but they can't yet see their cart.

We'll create the cart page in two steps:

● Create a cart component and set up routing to the new component. At this point, the cart page will
only have default text.
● Display the cart items.
Angular Services: Create the cart page
Generate a cart component, named cart. $ ng generate component cart
src/app/cart/cart.component.ts
import { Component , OnInit } from '@angular/core' ;

@Component ({
selector : 'app-cart' ,
templateUrl : './cart.component.html' ,
styleUrls : ['./cart.component.css' ]
})
export class CartComponent implements OnInit {

constructor () { }

ngOnInit () {
}

}
Angular Services: Create the cart page
Add routing (a URL pattern) for the cart component.

@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
RouterModule.forRoot([
{ path: '', component: ProductListComponent },
{ path: 'products/:productId', component: ProductDetailsComponent },
{ path: 'cart', component: CartComponent },
])
],
Angular Services: Create the cart page
To see the new cart component, click the "Checkout" button
Angular Services: Create the cart page
Services can be used to share data across components:
Display the cart items
Services can be used to share data across components:

The product details component already uses the cart service (CartService) to add products to the cart.
In this section, you'll update the cart component to use the cart service to display the products in the cart.

Open cart.component.ts.

Set up the component to be able to use the cart service. (This is the same way you set up the product
details component to use the cart service, above.)
Angular Services: Create the cart page
src/app/cart/cart.component.ts

import { Component } from '@angular/core' ;


import { CartService } from '../cart.service' ;
Inject the CartService to manage cart information.
export class CartComponent {
items; ///Define the items property to store the products in the cart.
constructor (
private cartService : CartService
) { }

ngOnInit () {
this.items = this.cartService .getItems(); //Set the items using the cart service's getItems()
method.

}
}
Angular Services: Create the cart page
Update the template with a header ("Cart"), and use a <div> with an *ngFor to display each of the cart
items with its name and price.
src/app/cart/cart.component.html

<h3>Cart</h3>

<div class="cart-item" *ngFor="let item of items" >


<span>{{ item.name }} </span>
<span>{{ item.price | currency }} </span>
</div>
Angular Services: Create the cart page

Test your cart component.

1. Click on "My Store" to go to the product list page.


2. Click on a product name to display its details.
3. Click "Buy" to add the product to the cart.
4. Click "Checkout" to see the cart.
5. To add another product, click "My Store" to return to the product list. Repeat the steps above.
Angular Services: Retrieve shipping prices

Data returned from servers often takes the form of a stream. Streams are useful because they make it
easy to transform the data that is returned, and to make modifications to the way data is requested. The
Angular HTTP client (HttpClient) is a built-in way to fetch data from external APIs and provide them to
your application as a stream.

Use the HTTP client to retrieve shipping prices from an external file.
Angular Services: Retrieve shipping prices

Predefined shipping data


For the purpose of this Getting Started guide, we have provided shipping data in assets/shipping.json.
You'll use this data to add shipping prices for items in the cart.
src/assets/shipping.json
[
{
"type": "Overnight",
"price": 25.99
},
{
"type": "2-Day",
"price": 9.99
},
{
"type": "Postal",
"price": 2.99
}
]
Angular Services: Retrieve shipping prices

Enable HttpClient for app


Before you can use Angular's HTTP client, you must set up your app to use HttpClientModule.
Angular's HttpClientModule registers the providers needed to use a single instance of the HttpClient service throughout your app. The
HttpClient service is what you inject into your services to fetch data and interact with external APIs and resources.

import { NgModule } from '@angular/core' ;


import { BrowserModule } from '@angular/platform-browser' ;
import { RouterModule } from '@angular/router' ;
import { HttpClientModule } from '@angular/common/ http';
import { NgModule } from '@angular/core' ;
import { BrowserModule } from '@angular/platform-browser' ;
import { RouterModule } from '@angular/router' ;
import { HttpClientModule } from '@angular/common/ http';
import { ReactiveFormsModule } from '@angular/forms' ;
import { AppComponent } from './app.component' ;
import { TopBarComponent } from './top-bar/top-bar.component' ;
import { ProductListComponent } from './product-list/product-list.component' ;
src/app/app.module.ts
import { ProductAlertsComponent } from './product-alerts/product-alerts.component' ;
import { ProductDetailsComponent } from './product-details/product-details.component' ;
@NgModule ({
imports : [
BrowserModule ,
HttpClientModule ,
ReactiveFormsModule ,
RouterModule .forRoot ([
{ path: '', component : ProductListComponent },
{ path: 'products/:productId' , component : ProductDetailsComponent },
{ path: 'cart' , component : CartComponent },
])
],
declarations : [
AppComponent ,
TopBarComponent ,
ProductListComponent ,
ProductAlertsComponent ,
ProductDetailsComponent ,
CartComponent ,
],
bootstrap : [
AppComponent
]
})
export class AppModule { }
Angular Services: Retrieve shipping prices
Enable HttpClient for cart service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
export class CartService {
items = [];
constructor(
private http: HttpClient
) {}

addToCart(product) {
this.items.push(product);
}

getItems() {
return this.items;
}

clearCart() {
this.items = [];
return this.items;
}

getShippingPrices() {
return this.http.get('/assets/shipping.json');
}
}
Angular Services: Retrieve shipping prices
Define the shipping page

Generate a new component named shipping. : ng generate component

add the route: { path: 'shipping' , component : ShippingComponent },

import { CartService } from '../cart.service'; // into shipping.component.ts


export class ShippingComponent implements OnInit {
shippingCosts;

constructor(
private cartService: CartService
) {
}

ngOnInit() {
this.shippingCosts = this.cartService.getShippingPrices();
}}
Angular Services: Retrieve shipping prices

shipping.component.html

<h3>Shipping Prices </h3>


<div class="shipping-item" *ngFor="let shipping of shippingCosts | async" >
<span>{{ shipping.type }} </span>
<span>{{ shipping.price | currency }} </span>
</div>

src/app/cart/cart.component.html

<h3>Cart</h3>

<p>
<a routerLink ="/shipping" >Shipping Prices </a>
</p>

<div class="cart-item" *ngFor="let item of items" >


<span>{{ item.name }} </span>
<span>{{ item.price | currency }} </span>
</div>
Angular Forms: definition

At the end of Managing Data & services, the online store application has a product catalog and a shopping cart.

In this part, you'll finish the app by adding a form-based checkout feature. You'll create a form to collect user information
as part of checkout.

Forms in Angular

Forms in Angular take the standard capabilities of the HTML based forms and add an orchestration layer to help with

creating custom form controls, and to supply great validation experiences. There are two parts to an Angular Reactive

form, the objects that live in the component to store and manage the form, and the visualization of the form that

lives in the template.


Angular Forms
import { Component } from '@angular/core'; src/app/cart/cart.component.ts
import { FormBuilder } from '@angular/forms';
import { CartService } from '../cart.service

export class CartComponent {


items;
checkoutForm;

constructor(
private cartService: CartService,
private formBuilder: FormBuilder,
) {
this.items = this.cartService.getItems();

this.checkoutForm = this.formBuilder.group({
name: '',
address: ''
});
}
}
Angular Forms

Add the following method into src/app/cart/component.ts to process the form

onSubmit(customerData) {
// Process checkout data here
console.warn('Your order has been submitted', customerData);

this.items = this.cartService.clearCart();//Use the CartService#clearCart() method to empty the cart


items and reset the form after it is submitted
this.checkoutForm.reset();
}
Angular Forms
src/app/cart/cart.component.html
<h3>Cart</h3>
<p>
<a routerLink ="/shipping" >Shipping Prices </a>
</p>

<div class="cart-item" *ngFor="let item of items" > use an ngSubmit event binding to listen
<span>{{ item.name }} </span> for the form submission and call the
<span>{{ item.price | currency }} </span> onSubmit() method with the
</div> checkoutForm value.
<form [formGroup ]="checkoutForm" (ngSubmit )="onSubmit(checkoutForm.value)" >
<div> Use a formGroup property binding to bind
<label for="name"> the checkoutForm to the form tag in the
Name template.
</label>
<input id="name" type="text" formControlName ="name"> Add input fields for name and address. Use
</div> the formControlName attribute binding to
<div> bind the checkoutForm form controls for
<label for="address" > name and address to their input fields. The
Address final complete component is shown below:
</label>
<input id="address" type="text" formControlName ="address" >
</div> Also include a "Purchase" button to submit
<butto n class="button" type="submit" >Purchase </button> the form.
</form>
Angular Forms: Intoduction
Fin Session 5
Building a Web App with Angular 8
Managing Data & Services
json File & HttpClient

You might also like