import { Component } from '@angular/core' ; import { Router } from '@angular/router' ; import { Product , ProductService } from './product.service' ; import { ProductCardComponent } from './product-card.component' ; import { CartService } from '../cart/cart.service' ; @ Component ( { selector : 'db-product-grid' , templateUrl : 'app/product/product-grid.component.html' } ) export class ProductGridComponent { products : any = [ ] ; constructor ( private router , private productService , private cartService ) { this . router . routerState . root . queryParams . subscribe ( params => { let category = params [ 'category' ] ; let search = params [ 'search' ] ; let products = this . productService . getProducts ( category , search ) ; this . products = this . transform ( products ) ; } ) ; } transform ( source ) { let index = 0 ; let length = source . length ; let products = [ ] ; while ( length ) { let row = [ ] ; if ( length >= 3 ) { for ( let i = 0 ; i < 3 ; i ++ ) { row . push ( source [ index ++ ] ) ; } products . push ( row ) ; length -= 3 ; } else { for ( ; length > 0 ; length -- ) { row . push ( source [ index ++ ] ) ; } products . push ( row ) ; } } return products ; } addToCart ( product ) { this . cartService . addProduct ( product ) ; } }