angular2中的无限滚动,用于子数据加载75%

时间:2018-01-02 14:15:46

标签: json angular2-routing angular2-services angular2-directives infinite-scroll

我想创建无限滚动功能,其中最初只有JSON数据的第一个值加载,即第一篇文章应该加载,然后向下滚动到页面的3/4(75%)部分加载底部的下一篇文章下一个加载的文章也会发生同样的事情。  我使用角度js与rxjs可观察: https://codeburst.io/angular-2-simple-infinite-scroller-directive-with-rxjs-observables-a989b12d4fb1

下面是代码: app.component.ts

import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { NewsService } from './news.service';
import { NavBarComponent } from './navbar.component';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
  providers: [NewsService]
})
export class AppComponent {

 currentPage: number = 1;

  news: Array<any> = [];

  scrollCallback;

  constructor(private newsService: NewsService) {

    this.scrollCallback = this.getStories.bind(this);
  }

  getStories() {
    return this.newsService.getLatestStories(this.currentPage).do(this.processData);
  }

  private processData = (news) => {
    this.currentPage++;
    this.news = this.news.concat(news.json());
    console.log(this.news);
  }

}

news.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

const BASE_URL = 'https://www.eremnews.com/wp-json/wp/v2/posts?minified=true';

@Injectable()
export class NewsService {

  constructor(private http: Http) { }

  getLatestStories(page: number = 1) {
    return this.http.get(`${BASE_URL}/news?page=${page}`);
  }

}

app.component.html

<ul id="infinite-scroller"
  appInfiniteScroller
  scrollPerecnt="70"
  immediateCallback="true"
  [scrollCallback]="scrollCallback">
    <li *ngFor="let x of news">

     <h1>{{x.title.rendered | json}}</h1> <br>
    <figure style="padding:20px"><img [src]="x.post_thumbnail.thumbnail"></figure> 
      <div class="details">
        <p>{{x.content.rendered |json}}</p><br>
      </div>
      <p>{{x.date_gmt_lang |json}}</p>

    </li>
</ul>

在我的代码中,最初,所有数据都是在第一页加载的。我想在页面上加载文章,只在路由器URL中我想显示文章的ID。

1 个答案:

答案 0 :(得分:0)

您必须确保ul元素具有滚动条,如源代码app.component.scss中所示。 html中的[]属性immediateCallback

否则,请将您的代码与工作source

进行比较