title: How to push data into array in Angular 2 when using similar route
body: <p>So far, I haven't found a simple example of how to push data into an array in Angular 2. In AngularJs it was easy (<a href="http://jsfiddle.net/7n8NR/3/" rel="nofollow noreferrer">example</a>), but I'm struggling for it in Angular 2, maybe because I'm using router and I don't know how to configure it (I was following the angular <a href="https://angular.io/tutorial/toh-pt5" rel="nofollow noreferrer">heroes example</a>).</p>
  
  <p>What I want to do, the whole solution:</p>
  
  <p><strong>app.module.ts:</strong></p>
  
  <pre><code>import { NgModule } from "@angular/core";
  import { BrowserModule } from "@angular/platform-browser";
  import { FormsModule } from '@angular/forms';
  import { RouterModule } from '@angular/router';
  import { LocationStrategy, HashLocationStrategy } from '@angular/common';
  import { HttpModule } from '@angular/http';
  import { ProductsService } from '../services/ProductsService';
  
  
  import { AppComponent } from "./components/app";
  import { Products } from "./components/products";
  
  @NgModule({
      imports: [
          BrowserModule,
          FormsModule,
          HttpModule,
          RouterModule.forRoot([
              {
                  path: 'products/:class_id/:type_id',
                  component: Products
              }
          ], { useHash: true })
      ],
      exports: [RouterModule],
      declarations: [
          AppComponent
          Products
      ],
      providers: [
          ProductsService
      ],
      bootstrap: [AppComponent]
  })
  export class AppModule { }
  </code></pre>
  
  <p><strong>AppComponent.ts</strong></p>
  
  <pre><code>import { Component} from "@angular/core";
  
  @Component({
      selector: "my-app",
      template: `&lt;div&gt;
                  &lt;a [routerLink]="['/products', 1, 1]"&gt;Products-1&lt;/a&gt;
                  &lt;a [routerLink]="['/products', 2, 2]"&gt;Products-2&lt;/a&gt;
                 &lt;/div&gt;`
  })
  export class AppComponent{}
  </code></pre>
  
  <p><strong>ProductsService.ts</strong></p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { Headers, Http } from '@angular/http';
  import 'rxjs/add/operator/toPromise';
  
  @Injectable()
  export class ProductsService {
  
      private headers = new Headers({ 'Content-Type': 'application/json' });
  
      constructor(private http: Http) { }
  
      getProducts(class_id: string, type_id: string, index: number, numberOfObjectsPerPage: number): Promise&lt;any&gt; {
          return this.http.get('Home/GetProducts?pageIndex=' + index +'&amp;classId=' + class_id + '&amp;typeId=' + type_id)
              .toPromise()
              .then(response =&gt; response.json() as any)
              .catch(this.handleError);
      }
  
      private handleError(error: any): Promise&lt;any&gt; {
          console.error('An error occurred', error); // for demo purposes only
          return Promise.reject(error.message || error);
      }
  }
  </code></pre>
  
  <p><strong>Product.ts</strong></p>
  
  <pre><code>import 'rxjs/add/operator/switchMap';
  import { Component, OnInit } from '@angular/core';
  import { ActivatedRoute, ParamMap } from '@angular/router';
  import * as $ from 'jquery';
  
  import { ProductsService } from '../../services/ProductsService';
  import { Product } from '../../common/models/Product';
  
  @Component({
      selector: 'products',
      templateUrl: 'Products.html',
  })
  export class Products implements OnInit {
      products: Array&lt;Product&gt; = [];
      numberOfObjectsPerPage: number = 10;
      index: number = 0;
      constructor(
          private productsService: ProductsService,
          private route: ActivatedRoute
      ) {}
  
      ngOnInit(): void {
          this.loadProducts();
      }
  
      loadProducts():void{
          this.route.paramMap
              .switchMap((params: ParamMap) =&gt;
                  this.productsService.getProducts(params.get('class_id'), params.get('type_id'), this.index, this.numberOfObjectsPerPage))
              .subscribe(products =&gt; {
                  this.products = products;
          });
      }
  
      showMore():void{
          this.index++;
          this.loadProducts();
      }
  }
  </code></pre>
  
  <p><strong>Products.html:</strong></p>
  
  <pre><code>&lt;div class="product" *ngFor="let product of products;"&gt;
    {{ product.name }}
  &lt;/div&gt;
  &lt;button (click)="showMore()"&gt;Show more&lt;/button&gt;
  </code></pre>
  
  <p>So, what is the problem here: if I go to <code>Products-1</code> I get 10 products, which is obvious, but if I press <code>Show more</code> then the first 10 products are removed and another 10 are shown - which again is obvious, so to avoid this and keep the first 10 and load 10 more, I replaced <code>Product.ts -&gt; this.products = products;</code> to:</p>
  
  <pre><code> for (let i = 0; i &lt; products.length; i++) {
    this.products.push(products[i]);
   }
  </code></pre>
  
  <p>Another problem appears now: when I go to <code>Product-2</code>, the products from <code>Products-1</code> are shown along with the products of <code>Product-2</code>, so to avoid this, I added this two lines into the <code>Product.ts constructor:</code></p>
  
  <pre><code>constructor(private productsService: ProductsService, private route: ActivatedRoute) {
          route.paramMap.subscribe(params =&gt; this.products = []);
          route.paramMap.subscribe(params =&gt; this.index = 0);
  }
  </code></pre>
  
  <p>Now, everything works just fine except: when I go from <code>Products-1</code> to <code>Products-2</code> and load more products, and after that return to <code>Products-1</code>, I can see in my network tab that multiple requests of same type are being send to my server.</p>
  
  <p>So my questions are:</p>
  
  <ol>
  <li>Is there a better way to push data when using routing, and avoid to reset the parameters in the constructor ?</li>
  <li>If the pushing into the array is okay, and if it is okay to reset the parameters in the constructor, then, how to avoid multiple requests when going from one route to another ? </li>
  </ol>