首页 > 解决方案 > Angular如何将json数组对象转换为对象数组?

问题描述

我正在研究角度项目并从 JSON 对象创建分页,例如Example

如果我从 .ts 文件中放入虚拟 JSON 对象数组,如上例所示,我的代码可以正常工作。但是,当我从 HTTP 请求中获得相同的对象数组时,它会在我的浏览器控制台中显示以下错误。

在此处输入图像描述

我认为 JSON Array of Objects 没有正确映射到我的 Array of Object 类型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' 
      }
    ];

一切正常。这是一个输出:

在此处输入图像描述

这是此链接的工作示例:

在此处输入图像描述

请帮助我解决我做错了什么。

标签: arraysjsonangular

解决方案


将 setPage 函数也移动到服务成功函数中,以便在切片时可以使用帖子、getFliteredData。

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(json => {
    this.posts = json;      
    this.getFilteredData = this.posts;
    this.rows = 100;
    this.setPage(1);  
  }).

推荐阅读