我想创建无限滚动功能,其中最初只有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。
您必须确保ul
元素具有滚动条,如源代码app.component.scss中所示。 []
在qtml中的immediateCallback
属性。
否则,将您的代码与工作source进行比较