1/17/2019

New

  • Services
  • Routing

We can move some logic into a new file. In Angular, these are called services.

Services encourage reusable code.

Let's make a service to retrieve menu items.

  • ng g s shared/services/menu-items
  • ng g i shared/interfaces/menu-item

  • Add fields to your interface.
  • Create 'getMenuItems' in the service

    public getMenuItems(): Array{
    return [
      {
        id: 1,
        name: "Taco",
        description: "Just a Taco",
        category: "Tacos",
        price: 1.5,
        isFeatured: false
    },
    {
        id: 2,
        name: "TacocaT",
        description: "A Palindrome",
        category: "Tacos",
        price: 2.2,
        isFeatured: false
    }
    ]
  }
    

Ignore that /MenuItem tag

Call the service in our taco-menu component

Add it to the constructor


	constructor(private menuService: MenuItemsService)

Call it in ngOnInit


    let x: Array = this.menuService.getMenuItems();
    console.log(x);
    

That was a very simple service!

A true service will make a call out to the web (some url) to retrieve data. Another common use for a service is to return data from a local .json file.

Routing

Routing allows us to navigate between pages easily.

A bit of cleanup: comment out app-taco-menu and make sure router-outlet was included in app-component.html


	

	
 

Writing out your routes.

These are done inside the app-routing.module.ts. Make sure to import TacoMenuComponent and to create a placeholder MenuDetailComponent.


const routes: Routes = [
    { path: '', redirectTo: '/menu', pathMatch: 'full' },
    { path: 'menu', component: TacoMenuComponent },
    { path: 'detail/:id', component: MenuDetailComponent }
];
    

Leveraging Route Parameters

We can use route parameters to create unique looking pages. Remember seeing the route for


        { path: 'detail/:id', component: MenuDetailComponent }
    

The :id represents a dynamic routing parameter.

Retrieving a routing parameter

  • import { ActivatedRoute, Params } from '@angular/router';
  • import { MenuItemsService } from '../shared/services/menu-items.service';
  • import { MenuItem } from '../shared/interfaces/menu-item';

menu-detail.component.ts


export class MenuDetailComponent implements OnInit {

  constructor(private route: ActivatedRoute, private menuService: MenuItemsService) { }
  currentMenuItem: MenuItem;
  ngOnInit() {
    this.route.params.forEach((params: Params) => {
      if(params['id'] !== undefined){
        const id:number = +params['id'];
        this.currentMenuItem = this.getDetail(id);
      }
    });
  }
  getDetail(id: number){
    return this.menuService.getMenuItemsById(id);
  }

}
    

menu-items.service.ts


 public getMenuItemsById(id: number): MenuItem{
    
    return this.getMenuItems().find(element => {
      return element.id === id;
    })
  }
    

menu-detail.component.html


  

{{currentMenuItem.name}}

>