Building A Web App With Angular Managing Data Servicesjson File HttpClient
Building A Web App With Angular Managing Data Servicesjson File HttpClient
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 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).
● 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
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
@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
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.
<div *ngIf="product">
<h3>{{ product.name }} </h3>
<h4>{{ product.price | currency }} </h4>
<p>{{ product.description }} </p>
● 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
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>
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
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
constructor(
private cartService: CartService
) {
}
ngOnInit() {
this.shippingCosts = this.cartService.getShippingPrices();
}}
Angular Services: Retrieve shipping prices
shipping.component.html
src/app/cart/cart.component.html
<h3>Cart</h3>
<p>
<a routerLink ="/shipping" >Shipping Prices </a>
</p>
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
constructor(
private cartService: CartService,
private formBuilder: FormBuilder,
) {
this.items = this.cartService.getItems();
this.checkoutForm = this.formBuilder.group({
name: '',
address: ''
});
}
}
Angular Forms
onSubmit(customerData) {
// Process checkout data here
console.warn('Your order has been submitted', customerData);
<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