So far I have not found a simple example of how to transfer data to an array in Angular 2. In AngularJs it was easy ( example ), but I am afraid for it in Angular 2, maybe because I use a router and I don’t know how to configure it (I followed the Angular example of heroes ).
What I want to do is the whole solution:
app.module.ts:
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 { }
AppComponent.ts
import { Component} from "@angular/core";
@Component({
selector: "my-app",
template: `<div>
<a [routerLink]="['/products', 1, 1]">Products-1</a>
<a [routerLink]="['/products', 2, 2]">Products-2</a>
</div>`
})
export class AppComponent{}
ProductsService.ts
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<any> {
return this.http.get('Home/GetProducts?pageIndex=' + index +'&classId=' + class_id + '&typeId=' + type_id)
.toPromise()
.then(response => response.json() as any)
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
Product.ts
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<Product> = [];
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) =>
this.productsService.getProducts(params.get('class_id'), params.get('type_id'), this.index, this.numberOfObjectsPerPage))
.subscribe(products => {
this.products = products;
});
}
showMore():void{
this.index++;
this.loadProducts();
}
}
Products.html:
<div class="product" *ngFor="let product of products;">
{{ product.name }}
</div>
<button (click)="showMore()">Show more</button>
So, what’s the problem: if I go to Products-1, I will get 10 products, which is obvious, but if I click Show more, the first 10 products will be deleted, and another 10 - obviously, therefore, to avoid this and save the first 10 and load another 10 I replaced Product.ts -> this.products = products;with:
for (let i = 0; i < products.length; i++) {
this.products.push(products[i]);
}
: Product-2, Products-1 Product-2, , , Product.ts constructor:
constructor(private productsService: ProductsService, private route: ActivatedRoute) {
route.paramMap.subscribe(params => this.products = []);
route.paramMap.subscribe(params => this.index = 0);
}
, : Products-1 Products-2 , Products-1, .
, :