Angular:无限滚动加载(ajax)

时间:2017-07-26 10:36:39

标签: angular typescript observable angular-cli

问题是从JSON文件实现无限滚动加载数据。

我有一项服务,其中定义了方法getDataFromJson()。它的方法处理来自JSON文件的数据,创建将在应用程序中使用的自定义对象,并使用此自定义对象返回数组。

product.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from "@angular/http";
import { Product } from '../model/product';
import { Observable } from "rxjs";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class ProductService {

  private productsList$: Observable<Product[]>;

  constructor(private http: Http) {
    this.productsList$ = this.getDataFromJson();
  }

  /* Get Data From JSON file */
  getDataFromJson(): Observable<any> {
    return this.http.get('assets/data.json')
      .map((resp: Response) => {
        let prodList = resp.json().product;
        let list: Product[] = [];
        for (let index in prodList) {
          let product = prodList[index].data;
          list.push({
            id: product.id_product,
            category: product.categoryTitle,
            description: product.systemdescription,
            systitle: product.systitle,
            fireresistance: product.fireresistance,
            soundproof: product.soundproof,
            wallthickness: product.wallthickness,
            dampingstrength: product.dampingstrength
          })
        }
        return list;
      })
      .catch((error: any)=> { return Observable.throw(error);});
  }

  getProducts(): Observable<Product[]> {
    return this.productsList$;
  }

}

之后,在Products Component我使用该方法并渲染我的产品列表。

products.component.ts

import {Component, OnInit} from '@angular/core';
import {Product} from "../model/product";
import {ProductService} from "../services/product.service";
import {WatchlistService} from "../services/watchlist.service";

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
  public products: Product[] = [];

  constructor(private prodService: ProductService) { }

  ngOnInit() {
    this.prodService.getProducts()
      .subscribe(
        data => this.products = data,
        error => console.log(error)
      );
  }

}

products.component.html

<div class="row">
  <div class="col-md-9">
    <app-product-list
      [products]="products"></app-product-list>
  </div>
  <div class="col-md-3">
    <app-product-filters></app-product-filters>
  </div>
</div>

当然,所有产品都在Products Component呈现。但我需要在第一次初始化组件时加载前10个产品。用户滚动到屏幕底部后,加载了以下5个元素。

那么,我可以在滚动时从数组中逐步加载数据并同时使用可观察的方法吗? 如果有可能,我该怎么做?也许,有人已经遇到过这样的问题吗?

0 个答案:

没有答案