gpt4 book ai didi

json - 如何将从服务接收到的数据传递到 Angular 数据表

转载 作者:行者123 更新时间:2023-12-01 05:34:44 26 4
gpt4 key购买 nike

我刚刚开始研究 Angular 4,我正在尝试将我从 json 格式的 angular 服务接收到的一些数据渲染到 angular-datatable 中,但是无论我尝试哪个选项都不适合我。
表来了,列来了,但是列内的数据没有显示。

任何帮助都会很棒,

提前致谢..!!!!

请在下面找到我的代码:

组件.html

<table datatable [dtOptions]="dtOptions" class="row-border hover"></table>

组件.ts
import { Component, OnInit } from '@angular/core';
import { FleetDataService } from '../../services/fleet-data.service';
import { Subject } from 'rxjs/Subject';

@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})

export class DashboardComponent implements OnInit {

private fleetData: any;
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
constructor(private getFleetData:FleetDataService) { }

ngOnInit() {
this.getFleetData.getFleetData().subscribe(
fleetData => {
this.fleetData = fleetData;
console.log(this.fleetData);
this.dtTrigger.next();
},
err => {
console.log(err);
}
);
this.dtOptions = {
pagingType: 'full_numbers',
columns: [{
title: 'First Name',
data: this.fleetData
}, {
title: 'Last Name',
data: this.fleetData
}, {
title: 'Score',
data: this.fleetData
}]
};
}
}

组件服务
import { Injectable } from '@angular/core';
import { HttpModule, Http, Response, Headers, RequestOptions } from
'@angular/http';
import { Observable } from 'rxjs/Rx';


@Injectable()
export class FleetDataService {

constructor(private http: Http) { }

getFleetData() {
return this.http.get("../../assets/data/test.json")
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server
Error'));
}

}

test.json
  [{
"FirstName": "Jill",
"LastName": "Smith",
"Score": "disqualified"
}, {
"FirstName": "Eve",
"LastName": "Jackson",
"Score": "94"
}, {
"FirstName": "John",
"LastName": "Doe",
"Score": "80"
}, {
"FirstName": "Adam",
"LastName": "Johnson",
"Score": "67"
}]

最佳答案

您在订阅之外设置了 dtOptions。

如果你这样做,fleetData 会保持为空,所以 dtOptions 永远不会被正确设置,因为 Observable 是异步的。我提出这个代码:

export class DashboardComponent implements OnInit {

dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();

constructor(private getFleetData:FleetDataService) { }

ngOnInit() {
this.getFleetData.getFleetData().subscribe(
fleetData => {
console.log(fleetData);
this.buildDtOptions(fleetData)
this.dtTrigger.next();
},
err => {
console.log(err);
});
}

private buildDtOptions(fleetData: any): void {
this.dtOptions = {
pagingType: 'full_numbers',
columns: [
{title: 'First Name', data: fleetData},
{title: 'Last Name', data: fleetData},
{title: 'Score', data: fleetData}
]
};
}
}

对于此错误: ERROR TypeError: Cannot read property 'aDataSort' of undefined .您可以在 View 中执行微调器(ngIf/else),并在加载数据时显示数据表

关于json - 如何将从服务接收到的数据传递到 Angular 数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47527954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com