我正在学习Angular 2,我想在PHP中使用API数据填充ng2表,我有一个返回数据的服务,但我不知道如何填充数据变量订阅服务的数据。我正在调用服务方法getLanguages()。
我的服务代码是:
/get entered texts from the edittexts,and convert to integers.
Integer value1 = Integer.parseInt(sand1.getText().toString());
//doing a calculation
Double calculatedValue1 = (9.5*value1);
//set the value to the textview, to display on screen.
result1.setText("$"+ String.format( "%.2f", calculatedValue1 ));
我的组件代码是:
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);
}
}
我已经测试了服务并且正在返回数据,如何在构造函数中填充变量this.data以及我函数中的服务的数据结果?
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);
}
}
感谢
答案 0 :(得分:5)
我解决了在onChangeTable中调用服务并在subscribe方法中加载数据的问题。
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)
}