ng g s shared/services/menu-items
ng g i shared/interfaces/menu-item
public getMenuItems(): Array
Ignore that /MenuItem tag
Add it to the constructor
constructor(private menuService: MenuItemsService)
Call it in ngOnInit
let x: Array
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 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
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 }
];
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.
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}}