Building Cart service, data binding, update component in Angularjs

in #utopian-io8 years ago (edited)

Repository

https://github.com/angular/angular

What Will I Learn?

I Will learn
• Two way data binding
• Building the Cart Service
• Update a different component with data from an observable.

Requirement.

• Typescript version 2.4.2
• Node version 8.9.4
• Npm version 5.6.0
Bootstrap 4.0
• Visual Studio Code IDE

Two way data binding.

Two way data binding is important for form fields, where we bind the data input on a form to a variable in the component. In the signup component, we need to bind the username, name, email and password field to the signupData object on the component.
Its quite easy, we need import the forms modules to the app.module.ts and add the it to the import array.

Next on the signup.component.html we add the ngModel to bind data from the signupData object and also add the ngModelOptions.
Example binding the input from the name field to the signupData.name propertie.

[(ngModel)]="signupData.name

On the form element add the method to submit the form using ngSumbit which is bound to the signup method on the component. Once the submit button is clicked, it triggers the signup method on the component.

<div class="signup__container">
  <div class="container">
      <form class="form-signin" (ngSubmit)="signup()" #signupForm="ngForm">
          <div class="alert alert-warning alert-dismissible  fade show" role="alert" *ngIf="message !== ''">
              <strong>Hey!</strong> {{message}}
              <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
        <div class="text-left mb-4">
          <h1 class="h3 mb-3 font-weight-normal">Create an Account</h1>
          <p> Create a free Voltron account to order any kind of food. Already have a Voltron account? <a  class="link" routerLink="/login">Log in here</a></p>
        </div>
    
        <div class="form-label-group">
          <input type="name" id="inputName" class="form-control" [(ngModel)]="signupData.name" [ngModelOptions]="{standalone: true}" placeholder="Full Name" required autofocus>
          <label for="inputName">Name</label>
        </div>

        <div class="form-label-group">
            <input type="username" id="inputUsername" [(ngModel)]="signupData.username" class="form-control" [ngModelOptions]="{standalone: true}" placeholder="Username" required autofocus>
            <label for="inputUsername">Username</label>
        </div>

        <div class="form-label-group">
            <input type="email" id="inputEmail" class="form-control"[(ngModel)]="signupData.email" placeholder="Email address" [ngModelOptions]="{standalone: true}" required autofocus>
            <label for="inputEmail">Email address</label>
        </div>
    
        <div class="form-label-group">
          <input type="password" id="inputPassword" [(ngModel)]="signupData.password" class="form-control" placeholder="Password" [ngModelOptions]="{standalone: true}" required>
          <label for="inputPassword">Password</label>
        </div>
    
        <div class="checkbox mb-3">
          <label>
            <input type="checkbox" value="remember-me"> Remember me
          </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Create Account</button>
        <p class="mt-5 mb-3 text-muted text-center">&copy; 2017-2018</p>
      </form>
  </div>
</div>

Showing error flash messages
We add a snippet of code on the signup.component.html and use the directive *ngIf to toggle the display.

       <strong>Hey!</strong> {{message}}
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
</div>

The code *ngIf="message !== ''" on the div makes the flash message to show only when the server returns a message.

Building the Cart Service.

Generate the service from the command

Find cart.service.ts in `voltron/src/app/cart.service.ts

We need to add two imports below,

import {Item} from '../item';

The first import, "Subject" is of the rxjs library which used to set data an observable, the second import "Item" is the interface.

We need to create a cart item array to hold the objects(item) entering the cart.

cartItems: Item[] = []

In creating an observable we need a subject, which is the source and an announcer that tells the application that something has changed in the observable. Other component subscribes or listen or a change or mutation of the data in the source.

cartAnnouncer$ = this.cartAnnouncerSource.asObservable();

We need a method to announce to the application that an item has been added to the observable.

  return this.cartAnnouncerSource.next(item);
}

The next() method is actually telling the observable to announce the newly added item to the observable.
Lets head back to the item-feed.component.ts and add a variable called cartItems of which is going to be set to an empty array in the constructor method. Add the method that listens to the click event on the item.component.html

    if (!this.cartService.cartItems.includes(item)) {
      this.cartService.cartItems.push(item);
      this.cartService.announceCartItem(item);
      this.cartItems = this.cartService.cartItems;
    }
  }

The onAddItemTocart()method, checks if the cartService.cartItems array has the specific item, don't add the item when its clicked else add the item to the cart service and announce the item added to the observable.

Finally we set the value of cartItem in the component to the one on the service.

import { Component, OnInit } from '@angular/core';
import { ItemService } from '../item.service';
import { CartService } from '../cart.service';
import {Item} from '../../item';


@Component({
  selector: 'app-items-feed',
  templateUrl: './items-feed.component.html',
  styleUrls: ['./items-feed.component.sass']
})
export class ItemsFeedComponent implements OnInit {
 items: object;
 cartItems:Item[]


  constructor(
    private itemService: ItemService,
    private cartService: CartService
  ) {
    this.cartItems = []
  }
  ngOnInit() {
    this.getItems();
  }
  

  getItems(): void {
    this.itemService.getItems()
        .subscribe(items => {
          this.items = items['result']
        });
  }

  onAddItemToCart (item) {
    if (!this.cartService.cartItems.includes(item)) {
      this.cartService.cartItems.push(item);
      this.cartService.announceCartItem(item);
      this.cartItems = this.cartService.cartItems;
    }
  }
 
}

Update a different component with data from an observable.

It quite easy, we need to update the navbar component to show the amount of items in the observable once it's clicked.
So in the navbar component, we need to Subscribe to the observable, and check the length property of the array and set it to a counter in the navbar component, lastly we display it using interpolation.

Open the app-navbar component , create a counter variable in the constructor an set it to a default of zero.

this.cartItemsCount = 0

Next we subscribe to the cartService.announer$ in our constructor and set the value gotten to the cartItemsCount.

      item => {
        this.cartItemsCount = cartService.cartItems.length;
      }
    )
    ```


Lastly, lets update the navbar and show the cartItemsCount using interpolation.

 ```<a routerLink="/items/order"><i class="fa fa-cart-arrow-down"><span class="badge badge-light">{{ cartItemsCount }}</span></i></a>

Proof of Work Done

Github

Resource

https://angular.io/docs
http://reactivex.io/documentation/observable.html
https://getbootstrap.com/docs/4.0/getting-started/introduction/
https://angular.io/guide/form-validation

Sort:  

Your content is plagiarized from elsewhere on the web.
Here is a source where similar content is available
You have been banned from receiving Utopian Reviews.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Congratulations @zulfikarwahab! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @zulfikarwahab! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.094
BTC 63540.09
ETH 1790.10
USDT 1.00
SBD 0.39