【发布时间】:2018-04-19 09:15:11
【问题描述】:
我正在尝试对我正在显示的表格实施分页,但我收到了Cannot read property 'length' of undefined。
这是我的组件.ts
getdata: any[];
curPage: number;
pageSize: number;
ngOnInit() {
this.getData();
}
getData() {
let headers = new Headers();
headers.set('Content-Type', 'application/json');
let getUrl = 'http://jsonstub.com/v1/configs';
return this.http.get(getUrl, {headers: headers})
.subscribe(res => {
this.getdata = res.json();
console.log(this.getdata.length);
});
}
numberOfPages() {
return Math.ceil(this.getdata.length / this.pageSize);
};
我的 HTML 如下:
<tbody>
<tr *ngFor="let mem of getdata | FilterPipe: queryString | slice: (curPage * pageSize) - pagSize :curPage * pageSize">
<td>
<a (click)="getFormgroup(mem.configName) ? addtionalInfo = true : addtionalInfo = false" class="clickable">{{mem.configName}}</a>
</td>
<td>{{mem.sources.length}}</td>
<td>
<span *ngFor="let sourceNames of mem.sources; let last=last">
{{sourceNames.sourceId}}<span *ngIf="!last">, </span>
</span>
</td>
</tr>
<p class="pagination">
<button [disabled] = "curPage == 1" (click)="curPage = curPage - 1">PREV</button>
<span> Page {{curPage}} of {{ numberOfPages() }}</span>
<button [disabled] = "curPage >= getdata.length/pageSize" (click) = "curPage = curPage + 1">NEXT</button>
</p>
</tbody>
我的getdata 是一个长度为 4 的数组,如下所示。
[
{configName: "A", sources: Array(1), queryTimeThresholdInMs: 0},
{configName: "B", sources: Array(3), queryTimeThresholdInMs: 5},
{configName: "C", sources: Array(2), queryTimeThresholdInMs: 5},
{configName: "D", sources: Array(2), queryTimeThresholdInMs: 0}
]
我认为我的逻辑是正确的,而且我正在对数组执行getdata.length,因此不确定为什么会弹出此错误。
编辑:我通过getdata() 函数更新为在http.get 之后调用numberofPages(),但我得到了同样的错误。
getData() {
let headers = new Headers();
headers.set('Content-Type', 'application/json');
let getUrl = 'http://jsonstub.com/v1/configs';
return this.http.get(getUrl, {headers: headers})
.subscribe(res => {
this.getdata = res.json();
console.log(this.getdata);
},
() => {
this.numberOfPages();
});
}
【问题讨论】:
-
@Vega 它是一个表单组数组。
-
@Vega 好吧,我只是在
getdata中获取json 格式的数据,并将源部分显示为{{mem.sources.length}} -
您在哪一行得到错误?在
subscribe回调中,还是在return Math.ceil(this.getdata.length / this.pageSize)行中?因为当然你会在后一种情况下得到一个错误。 -
@kshetline 是的,我在返回语句中收到错误,在 HTML 中它指向
<button [disabled] = "curPage == 1" (click)="curPage = curPage - 1">PREV</button>
标签: angular typescript pagination