Tuesday, November 22, 2016

Angular 2 Part 3.3 - Model & Mock

In TypeScript, we can use classes to model our data. This helps us specify class property types that help our compiler ensure we're writing good code. I am going to model our car part by creating car-part.ts.

car-parts.ts
export class CarPart {
  id:number;
  name:String;
  price: number;
  description:String;
  inStock:number;
}
Mock is to separate our data file from component. It is good practice to keep our mock data separate from our model and component. I am going to move our data to mock.ts.

mock.ts
import {CarPart} from './car-part';

export const CARPARTS : CarPart[] = [{ 
  "id":1,
  "name":"Super Tires",
  "price":2.0,
  "description":"These tires are the very best",
  "inStock":5
},
{
  "id":2,
  "name":"Reinforced shocks",
  "price":4.99,
  "description":"Shock made from krytonite",
  "inStock":4
},
{
  "id":3,
  "name":"Padded Seats",
  "price":2,
  "description":"Super soft scats for a smooth ride.",
  "inStock":0
}] // Example of object
Now we going to integrate car-parts.ts and mock.ts into our car-parts.component.ts.
import {Component} from '@angular/core';
import {CarPart} from './car-part';
import {CARPARTS} from './mocks';

@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[];

  ngOnInit() {
    this.carParts = CARPARTS;
  }

  totalCarParts(){
    let sum = 0;
    for (let carPart of this.carParts) {
      sum += carPart.inStock;
    }
    return sum;
  }
}
ngOnInit() is invoked after the component is constructed and is the best place to initialize properly value.

For whole Part 3, we don't add any new functionality, but our code now is more easy to maintenance and scale. Let's look at our files structure.

  • index.html - Include <my-app> and load main.ts.
  • app\main.ts - Import and bootstraps our first component in app.component.ts.
  • app\app.component.ts - Load the header and sub component in car-parts.component.ts.
  • app\car-parts.component.ts - Our JavaScript.
  • app\car-part.ts - The data model.
  • app\mocks.ts - The fake data.
  • app\car-parts.component.html
  • app\car-parts.component.css
Download Car Part Source:

No comments:

Post a Comment