Monday, November 28, 2016

Angular 2 Part 5.3 - HTTP

In part 5.3, we are going to fetch our data using HTTP JSON call instead of mock data.

There are 5 steps to make it happen:

1. Create a JSON data file to simulate the data from the server - car-parts.json.
{
 "data" : [
  {
   "id":1,
   "name":"Super Tires",
   "price":2.0,
   "description":"These tires are the very best",
   "inStock":5,
   "image":"/images/example1.png",
   "featured":false,
   "quantity":0
  },
  {
   "id":2,
   "name":"Reinforced shocks",
   "price":4.99,
   "description":"Shock made from krytonite",
   "inStock":4,
   "image":"/images/example2.png",
   "featured":true,
   "quantity":0
  },
  {
   "id":3,
   "name":"Padded Seats",
   "price":2,
   "description":"Super soft scats for a smooth ride.",
   "inStock":0,
   "image":"/images/example3.png",
   "featured":false,
   "quantity":0
  }
 ]
}

2. We need to include HTTP and RxJS Libraries. The HTTP library provides the get call we will use to call across the internet. The RxJS library stands for Reactive Extensions and provides some advance tooling for our HTTP Calls. If you used the 5 minutes QuickStart, you have already included these libraries using systemjs.config.js.

3. Import HTTPModule in main.ts. We can skip adding HTTP as provider because it had already added in HTTPModule.
import {NgModule, Component} from '@angular/core';
import {AppComponent} from './app.component';
import {CarPartComponent} from './car-parts.component';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import { RacingDataService } from './racing-data.service';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

@NgModule ({
  imports:      [ BrowserModule, FormsModule, HttpModule ], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent ], // Import dependencies.
  bootstrap:    [ AppComponent ], // Indicate first component to launch.
  providers:  [ RacingDataService ] // Now all subcomponents can ask for (inject) our RacingDataService.
})

class AppModule {}

// Start the application in web browser.
platformBrowserDynamic().bootstrapModule(AppModule);
4. Now we can inject HTTP and using it in racing-data.service.ts.
import { CARPARTS } from './mocks';
import {CarPart} from './car-part';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class RacingDataService {

 constructor(private http: Http) {}

 getCarParts() {
  return this.http.get('app/car-parts.json')
   .map(response => <CarPart[]>response.json().data);
 }

}
response = data returned.
<CarPart[]> = Tells our TypeScript compiler to treat this like an arrays of CarPart.
response.json() = For each response, parse the string into JSON.
.data = The array we want is under the data keyword.

5. Since our service returns an observable, we need to subscribe to that data stream and tell our component what to do when our data arrives.
import {Component} from '@angular/core';
import {CarPart} from './car-part';
import { RacingDataService } from './racing-data.service';

@Component({
  selector: "car-parts", // Display in selector defined in app.component.ts
  templateUrl: "app/car-parts.component.html",
  styleUrls: ["app/car-parts.component.css"]
})

export class CarPartComponent {
  carParts : CarPart[];

  // Declare a constructor
  constructor (private racingDataService: RacingDataService) {}

  ngOnInit() {
    this.racingDataService.getCarParts()
      .subscribe(carParts => this.carParts = carParts); // When carParts arrive on our data stream, set it equal to our local carParts array.
  }

  totalCarParts(){
    let sum = 0;
      if(Array.isArray(this.carParts)) {
        for (let carPart of this.carParts) {
          sum += carPart.inStock;
        }
      };
    return sum;
  }

  upQuality(carPart){
    if (carPart.quantity < carPart.inStock) carPart.quantity++;
  }
 
  downQuality(carPart){
    if (carPart.quantity != 0) carPart.quantity--;
  }

}

That's all for Angular 2 sample and I hope you all enjoyed. Here are some tools you might interest.

  • Angualr Angury an Angular 2 debugging tool.
  • Angular CLI - Angular Command Line Interface for developer kicks start project really fast.
Download Car Part Source:
https://github.com/htsiah/angular2-carparts

No comments:

Post a Comment