Angular Как преобразовать объект массива json в массив объектов? - PullRequest
0 голосов
/ 27 апреля 2018

Я работаю над угловым проектом и создаю нумерацию страниц из JSON Object, например Пример .

Если я поместил фиктивный массив объектов JSON из файла .ts, как показано в примере выше, мой код работает нормально. Но когда я получаю тот же массив объектов из 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 голосов
/ 27 апреля 2018

Переместите функцию 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);  
  }).
0 голосов
/ 27 апреля 2018

Попробуйте сделать срез в обратном вызове 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);    
      })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...