【发布时间】:2018-04-26 22:40:44
【问题描述】:
我正在处理 Angular 项目并从 JSON 对象创建分页,例如 Example。
如果我从 .ts 文件中放入虚拟 JSON 对象数组,如上例所示,我的代码可以正常工作。但是当我从 HTTP 请求中获得相同的对象数组时,它会在我的浏览器控制台中显示以下错误。
我认为 JSON 对象数组未正确映射到我的对象数组类型 Posts。
这是我的代码 app.component.ts:
import {
Component,
OnInit
} from '@angular/core';
import * as _ from 'underscore';
import {
Http,
Headers,
RequestOptions,
Response
} from '@angular/http';
import {
Observable
} from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import {
post
} from 'selenium-webdriver/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
pagerService: PagerService = new PagerService();
columns: string[];
posts: any[];
getFilteredData: Object;
pagedItems: any[];
rows: number;
count: number;
// pager object
pager: any = {};
ngOnInit() {
this.columns = ['userId', 'id', 'title', 'body'];
this.count = this.columns.length;
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => {
this.posts = json;
})
this.getFilteredData = this.posts;
this.rows = 100;
// initialize to page 1
this.setPage(1);
}
constructor(private http: Http) {
}
onSearching(searchValue: string) {
this.getFilteredData = this.posts.filter((d: Posts) => {
return d.title.toLowerCase().includes(searchValue.toLowerCase())
});
this.rows = this.getFilteredData.length;
}
setPage(page: number) {
if (page < 1 || page > this.pager.totalPages) {
return;
}
// get pager object from service
this.pager = this.pagerService.getPager(this.rows, page);
// get current page of items
this.pagedItems = this.getFilteredData.slice(this.pager.startIndex, this.pager.endIndex + 1);
}
}
class Posts {
userId: number;
id: number;
title: string;
body: string;
constructor() {
}
}
class PagerService {
getPager(totalItems: number, currentPage: number = 1, pageSize: number = 10) {
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
let startPage: number, endPage: number;
if (totalPages <= 10) {
// less than 10 total pages so show all
startPage = 1;
endPage = totalPages;
} else {
// more than 10 total pages so calculate start and end pages
if (currentPage <= 6) {
startPage = 1;
endPage = 10;
} else if (currentPage + 4 >= totalPages) {
startPage = totalPages - 9;
endPage = totalPages;
} else {
startPage = currentPage - 5;
endPage = currentPage + 4;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = _.range(startPage, endPage + 1);
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages
};
}
}
当我替换这行代码时:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => {
this.posts = json;
})
使用以下虚拟数据:
this.posts = [
{
userId: 1,
id: 1,
title: 'Loreum ispum',
body: 'dummy text'
},
{
userId: 1,
id: 1,
title: 'Loreum ispum',
body: 'dummy text'
},
{
userId: 1,
id: 1,
title: 'Loreum ispum',
body: 'dummy text'
},
{
userId: 1,
id: 1,
title: 'Loreum ispum',
body: 'dummy text'
}
];
一切正常。这是一个输出:
这是此链接的工作示例:
请帮助我解决我做错了什么。
【问题讨论】:
-
将
this.posts赋值给this.getFilteredData时,其值为undefined。fetch是异步。查看Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 以了解有关异步代码的更多信息。 -
你可以试试:
if (this.getFilteredData) { this.pagedItems = this.getFilteredData.slice(this.pager.startIndex, this.pager.endIndex + 1); }