Andres Franco Andres Franco - 22 days ago 8
TypeScript Question

Load ng2-table data form API

I am learning Angular 2, and I want to fill a ng2-table using an API data in PHP, I have a service that returns the data, but I don't know how to fill the data variable with the subscribe data of the service. I am calling the service method getLanguages().

my service code is :

import { Injectable,bind} from '@angular/core';
import { Http,Response} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Language} from './language';
import { Observable } from 'rxjs/Observable';
import {APP_BASE_HREF} from '@angular/common';
@Injectable()
export class LanguageService {
private languagesUrl = '../languages/get_all_languages'; // URL to webapi
constructor(private http: Http) { }
getLanguages(): Observable<Language[]> {
return this.http.get(this.languagesUrl)
.map((responseData) => {

return responseData.json();
})
.catch(this.handleError);
}

getAllLanguages(){
return this.http.get(this.languagesUrl).map(res => res.json());
}

private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
return Observable.throw(errMsg);
}

}


My component code is :

import { Component,OnInit} from '@angular/core';
import { CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgIf} from '@angular/common'
import { Language } from './language';
import { LanguageService } from './language.service';
import {PAGINATION_DIRECTIVES} from 'ng2-bootstrap/ng2-bootstrap';
import {NG_TABLE_DIRECTIVES} from 'ng2-table/ng2-table'
import { Observable} from 'rxjs/Observable';
import {TableData} from './table-data';
@Component({
selector: 'languages_list',
templateUrl: '../app/core/Languages/language-list.component.html',
styleUrls: ['../app/core/Languages/language.component.css'],
directives: [NG_TABLE_DIRECTIVES, PAGINATION_DIRECTIVES, NgClass, NgIf, CORE_DIRECTIVES, FORM_DIRECTIVES]

})

export class LanguageComponent implements OnInit {

languages: Language[];
errorMessage: string;
mode = 'Observable';
public rows:Array<any> = [];
public columns:Array<any> = [
{title: 'Code', name: 'code',sort: 'asc'},
{title: 'Name', name: 'name', sort: 'asc'}
];
public page:number = 1;
public itemsPerPage:number = 10;
public maxSize:number = 5;
public numPages:number = 1;
public length:number = 0;


public config:any = {
paging: true,
sorting: {columns: this.columns},
filtering: {filterString: '', columnName: 'name'}
};


public data: Array<any> =[];


public constructor(private _languageService: LanguageService) {

this._languageService.getLanguages()
.subscribe(
languages =>this.languages =languages,
error => this.errorMessage = <any>error
)

this.length = this.data.length;
//this.data =[{"code":"en","name":"English"},{"code":"es","name":"Spanish"}];
//this.data =this.getLanguages();


// this.data =[{"code":"en","name":"English"},{"code":"es","name":"Spanish"}];


}

public ngOnInit():void {
this.onChangeTable(this.config);
// this.getLanguages();
}

public changePage(page:any, data:Array<any> = this.data):Array<any> {

let start = (page.page - 1) * page.itemsPerPage;
let end = page.itemsPerPage > -1 ? (start + page.itemsPerPage) : data.length;
return data.slice(start, end);
}

public changeSort(data:any, config:any):any {
if (!config.sorting) {
return data;
}

let columns = this.config.sorting.columns || [];
let columnName:string = void 0;
let sort:string = void 0;

for (let i = 0; i < columns.length; i++) {
if (columns[i].sort !== '') {
columnName = columns[i].name;
sort = columns[i].sort;
}
}

if (!columnName) {
return data;
}

// simple sorting
return data.sort((previous:any, current:any) => {
if (previous[columnName] > current[columnName]) {
return sort === 'desc' ? -1 : 1;
} else if (previous[columnName] < current[columnName]) {
return sort === 'asc' ? -1 : 1;
}
return 0;
});
}

public changeFilter(data:any, config:any):any {
if (!config.filtering) {
return data;
}

let filteredData:Array<any> = data.filter((item:any) =>
item[config.filtering.columnName].match(this.config.filtering.filterString));

return filteredData;
}

public onChangeTable(config:any, page:any = {page: this.page, itemsPerPage: this.itemsPerPage}):any {
if (config.filtering) {
Object.assign(this.config.filtering, config.filtering);
}
if (config.sorting) {
Object.assign(this.config.sorting, config.sorting);
}

let filteredData = this.changeFilter(this.data, this.config);
let sortedData = this.changeSort(filteredData, this.config);
this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData;
this.length = sortedData.length;
}

public getLanguages() {
return this._languageService
.getLanguages()
.subscribe(
languages => this.languages= languages,
error => this.errorMessage = <any>error);

}


}


I already test the services and is returning data, How I fill the variable this.data in the constructor with the data result of the service that I have in my function?

public getLanguages() {
return this._languageService
.getLanguages()
.subscribe(
languages => this.languages= languages,
error => this.errorMessage = <any>error);

}


thanks

Answer

I solve the problem calling the service in the onChangeTable and loading the data in the subscribe method.

 public onChangeTable(config:any, page:any = {page: this.page, itemsPerPage: this.itemsPerPage}):any {
    if (config.filtering) {
      Object.assign(this.config.filtering, config.filtering);
    }
    if (config.sorting) {
      Object.assign(this.config.sorting, config.sorting);
    }

       this._languageService.getLanguages()
         .subscribe(languages => {
            this.data =languages;
            this.length = this.data.length;
            let filteredData = this.changeFilter(this.data, this.config);
            let sortedData = this.changeSort(filteredData, this.config);
            this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData;
            this.length = sortedData.length;
        },error => this.errorMessage = <any>error)
  }