无法将web api服务数据绑定到角度为2的ng2-smart-table
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法将web api服务数据绑定到角度为2的ng2-smart-table相关的知识,希望对你有一定的参考价值。
我能够访问我的服务并获取数据,但我不知道如何将其绑定到ng2-smart-table。我需要在网格视图中显示数据类型的结构。 组件代码:table.component.ts
@Component({
selector: 'ngx-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss'],
providers: <any>[TableDataService]
})
export class TableComponent {
source: LocalDataSource;
settings = {
add: {
addButtonContent: '<i class="nb-plus"></i>',
createButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
},
edit: {
editButtonContent: '<i class="nb-edit"></i>',
saveButtonContent: '<i class="nb-checkmark"></i>',
cancelButtonContent: '<i class="nb-close"></i>',
},
delete: {
deleteButtonContent: '<i class="nb-trash"></i>',
confirmDelete: true,
},
columns: {
id: {
title: 'ID',
type: 'number',
},
firstName: {
title: 'First Name',
type: 'string',
},
lastName: {
title: 'Last Name',
type: 'string',
},
username: {
title: 'Username',
type: 'string',
},
email: {
title: 'E-mail',
type: 'string',
},
age: {
title: 'Age',
type: 'number',
},
},
};
private customers:Customer[] = [];
private errorMessage:any = '';
constructor(private tableDataService: TableDataService){
this.source = new LocalDataSource();
this.tableDataService.getCustomerData()
.subscribe(customers => this.customers = customers,
error => this.errorMessage = <any>error);
debugger;
this.source.load(this.customers);
}
}
HTML代码:table.component.html
<nb-card-body>
<ng2-smart-table [settings]="settings" [source]="customers" (deleteConfirm)="onDeleteConfirm($event)">
</ng2-smart-table>
服务代码:table.service.ts
getCustomerData():Observable<Customer[]> {
return this.http.get('http://localhost:51654/api/Customer/')
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res:Response) {
let body = res.json();
return body || [];
}
private handleError(error:any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
单独我能够访问价值客户到html页面,但是当我分配到ng2-smart-table时,source =“customers”不起作用。
答案
用customers
中的source
替换html
<ng2-smart-table [settings]="settings" [source]="source" (deleteConfirm)="onDeleteConfirm($event)">
</ng2-smart-table>
如果您仍有问题,也请尝试此操作
从服务中获取数据后,如下所示加载它
setTimeout(() => {
this.source.load(yourdata);
this.cd.markForCheck();
}, 0);
你需要注射ChangeDetectionRef
constructor(private cd: ChangeDetectorRef) {}
另一答案
试试这样:
source: LocalDataSource = new LocalDataSource();
errorMessage: string;
constructor(private service: TableDataService) {
this.service.getAdvertises()
.subscribe(data => {
this.source.load(data);
}, error => this.errorMessage = <any>error);
}
以上是关于无法将web api服务数据绑定到角度为2的ng2-smart-table的主要内容,如果未能解决你的问题,请参考以下文章
Angular 2 Select - 从 Web 服务问题中加载数据