I've been working on implementing infinite scroll functionality for my card elements. Within my data.service file, I have a variable called reload
that is utilized to determine whether more data needs to be loaded. This variable is set to true when the end of the page is reached, with the setting being handled by the app.component.
The actual population of content takes place in post.component, where the data.service containing the reload variable makes use of an http service to fetch data from a php server.
So far, I've been using observables to access the reload status repeatedly, but it seems that subscription only occurs once during initialization.
app.component.ts
import { Component, HostListener } from '@angular/core';
import * as M from 'materialize-css';
import { DataService } from './current/posts/post-card/data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'cosmos';
constructor(private scrollSet: DataService) {}
@HostListener('scroll', ['$event'])
onScroll(event:any) {
if (event.target.offsetHeight + event.target.scrollTop >= event.target.scrollHeight - 100) {
console.log("noww");
this.scrollSet.setValue(true);
}
}
}
post.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
import { DomSanitizer } from '@angular/platform-browser';
import { Title } from "@angular/platform-browser";
@Component({
selector: 'app-post-card',
templateUrl: './post-card.component.html',
styleUrls: ['./post-card.component.css']
})
export class PostCardComponent implements OnInit {
constructor(private data: DataService, public sanitizer: DomSanitizer, private titleService: Title) {
this.titleService.setTitle("Current Feed | Cosmos");
}
received = 'none';
posts: any = [];
ngOnInit() {
this.data.getPostData().subscribe(data =>
{
this.posts.push(data);
this.received='success';
},
error =>
{
this.received='error';
});
this.data.getValue().subscribe((value) => {
this.data.getPostData().subscribe(data =>
{
this.posts.push(data);
this.received='success';
},
error =>
{
this.received='error';
});
});
}
}
data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private reload: BehaviorSubject<boolean>;
constructor(private http: HttpClient) {
this.reload = new BehaviorSubject<boolean>(false);
}
fetchGap = 5; // define number of results to fetch
fetchEnd: number = 0;
setValue(newValue): void {
this.reload.next(newValue);
}
getValue(): Observable<boolean> {
return this.reload.asObservable();
}
getPostData(){
this.fetchEnd += this.fetchGap;
return this.http.get('http://localhost:1234/Server/getPosts.php?fetchEnd=' + this.fetchEnd + '&fetchGap=' + this.fetchGap);
}
}