Angular如何将json数组对象转换为Object数组?

时间:2018-04-26 22:40:44

标签: arrays json angular

我正在研究角度项目并从Example等JSON对象创建分页。

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

enter image description here

我认为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' 
      }
    ];

每件事都很好。这是一个输出:

enter image description here

以下是此链接的工作示例:

enter image description here

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

尝试将切片放入fetch回调中。

fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(json => {
        this.posts = json;
        //input your code here     
        this.getFilteredData = this.posts;        
        this.pagedItems = this.getFilteredData.slice(this.pager.startIndex, this.pager.endIndex + 1);    
      })

答案 1 :(得分:1)

将setPage函数也移动到服务成功函数,以便在切片时使用posts,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);  
  }).