Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Angular Example

Below is all the code for our Angular example coffee system. You can view the live example at the following URL.

Root Module

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { OrderformComponent } from './orderform/orderform.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    OrderformComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Root Component

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Coffeemate - Your Coffee Ordering System!';

  author: string;

  constructor() {
    this.author = "CS4640";
  }

}

app.component.html

<app-navbar></app-navbar>

<div class="container">
    <div class="row">
        <div class="col-sm-12">
            <h1></h1>
            <h2></h2>
        </div>
    </div>
    <app-orderform></app-orderform>
</div>

Drink Model

drink.ts

export class Drink {

    constructor(
        public size:"Small"|"Medium"|"Large",
        public numEspresso:number,
        public name:string,
        public price:number,
        public customer:string) {
   
    }
}
import { Component } from '@angular/core';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrl: './navbar.component.css'
})
export class NavbarComponent {

}
<nav class="navbar navbar-expand-lg bg-body-tertiary">
    <div class="container-fluid">
        <a class="navbar-brand" href="#">Coffemate</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavDropdown">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link active" aria-current="page" href="#">Home</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

Orderform Component

orderform.component.ts

import { Component } from '@angular/core';
import { Drink } from '../drink';
import { OrderService } from '../order.service';
import { Observable, throwError } from 'rxjs';

@Component({
  selector: 'app-orderform',
  templateUrl: './orderform.component.html',
  styleUrl: './orderform.component.css'
})
export class OrderformComponent {

    // the current drink
    drink:Drink;

    // the current order (an array of drink objects)
    public order:Array<Drink> = [];

    // sizes of drinks that someone can order
    sizes:Array<string>;

    response:any;

    constructor(
        private orderService:OrderService
    ) {
        this.drink = new Drink("Small",1,"",0,"");
        this.sizes = ["Small", "Medium", "Large"];

    }

    // Event handler to add a drink to the order
    addToOrder() {
        // push the current drink onto the order array
        this.order.push(this.drink);

        // create a new Drink object with default values
        this.drink = new Drink("Small",1,"",0,"");
    }

    submitOrder() {
        this.orderService.sendRequest(this.order).subscribe(
            (respData) => {
                this.response = respData;
            }
        );
    }   
}

orderform.component.html

<div class="row">
    <div class="col-sm-8">
        <p>Drink: </p>

        <p>Form data: </p>


        <form #orderForm="ngForm">

            <div class="mb-3">
                <label for="name" class="form-label">Name of Drink</label>
                <input [(ngModel)]="drink.name" required
                                  #drinkname="ngModel"
                                  [class.is-invalid]="drinkname.invalid && drinkname.touched"
                    type="text" class="form-control" id="name" name="name" placeholder="What drink would you like?">
                <small class="text-danger" [class.d-none]="drinkname.valid || drinkname.untouched">Drink name is required</small>
            </div>

            <div class="mb-3">
                <label for="size" class="form-label">Size of Drink</label>
                <select class="form-select" name="size" [(ngModel)]="drink.size">
                     <option *ngFor="let s of sizes"></option>
                </select>
            </div>

            <div class="mb-3">
                <label for="espresso" class="form-label">Number of Espresso Shots</label>
                <select class="form-select" name="espresso" [(ngModel)]="drink.numEspresso">
                     <option>1</option>
                     <option>2</option>
                     <option>3</option>
                     <option>4</option>
                     <option>5</option>
                     <option>6</option>
                     <option>7</option>
                </select>
            </div>

            <div class="mb-3">
                <label for="price" class="form-label">Price</label>
                <input [(ngModel)]="drink.price" 
                    type="number" class="form-control" name="price" placeholder="Name your own price!">
            </div>

            <div class="mb-3">
                <label for="customer" class="form-label">Customer</label>
                <input [(ngModel)]="drink.customer"
                    type="text" class="form-control" name="customer" placeholder="Who is the drink for?">
            </div>

            <div class="mb-3">
                <button (click)="addToOrder()" class="btn btn-success" 
                    [disabled]="orderForm.form.invalid">Add Item</button>
            </div>

        </form>
    </div>
    <div class="col-sm-4">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Your Cart</h5>
                <p class="card-text">Add each item to your cart, then click "Submit Order" to checkout.</p>
            </div>
            <ul class="list-group list-group-flush">
                <li *ngIf="order.length == 0" class="list-group-item text-center">
                    <i>Your cart is empty.</i>
                </li>
                <li *ngFor="let d of order" class="list-group-item">
                    <br>
                    <small><i> -  shots of espresso</i><br>
                        For: </small>
                </li>
            </ul>
            <div class="card-body text-center">
                <button class="btn btn-primary"
                    (click)="submitOrder()"
                    [disabled]="order.length == 0">Submit Order</button>
            </div>
        </div>
        <p>
        
        </p>
    </div>
</div>

Order Service

order.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

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

  constructor(
    private http:HttpClient
  ) { }

  // NOTE: update the URL when publishing to the server!  This should
  // connect to a PHP file on our actual server.  For the published
  // backend above, we would change this URL to:
  // https://cs4640.cs.virginia.edu/activities/angular/backend.php
  sendRequest(data:any):Observable<any> {
    // Send the data array as a JSON object in the BODY of the HTTP POST request
    return this.http.post("http://localhost:8080/backend.php",JSON.stringify(data));
  }

}

Back-End PHP Code

<?php
// REQUIRED HEADERS FOR CORS
// Allow access to our development server, localhost:4200
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT");


// Read JSON data from the BODY of the HTTP POST request
// from PHP's standard input
$json = file_get_contents("php://input");
$input = json_decode($json, true);

// Do processing of the data

$output = [
    "time" => date("Y-m-d g:i a"),
    "request" => $input
];

$cost = 0;
foreach ($input as $drink) {
    $cost += $drink["price"];
}

$output["price"] = $cost;

// Print out a JSON object back to the client
header("Content-Type: application/json");
echo json_encode($output, JSON_PRETTY_PRINT);