Currently, I am working on integrating ngx-infinite-scroll functionality. My goal is to extract the initial 5 posts from my "posts" array and populate them into the "shownPosts" array at the beginning. Subsequently, as the user continues scrolling down, I intend to add another set of 5 posts. However, I encountered an issue where my "posts" array appears empty while the site is still loading in the ngOnInit.
The peculiarity arises when, upon posterior inspection with a different function (checkPosts), all the Posts are present. What could be causing this discrepancy?
Upon loading the website, the console outputs the following:
In constructor, this.posts.length: 0
In ngOnInit, this.posts.length: 0
ERROR TypeError: Cannot read properties of undefined (reading 'title') core.mjs:6485
at HotComponent.ngOnInit (hot.component.ts:37:70)
at callHook (core.mjs:2542:1)
at callHooks (core.mjs:2511:1)
at executeInitAndCheckHooks (core.mjs:2462:1)
at refreshView (core.mjs:9499:1)
at refreshComponent (core.mjs:10655:1)
at refreshChildComponents (core.mjs:9280:1)
at refreshView (core.mjs:9534:1)
at refreshEmbeddedViews (core.mjs:10609:1)
at refreshView (core.mjs:9508:1)
After manually triggering the "checkPosts()" function through a button once the site has loaded, the console logs display:
In checkPosts, this.posts.length: 32
In checkPosts, this.posts[0].title: This is the first posts title.
hot.component.ts:
import ...
@Component({
...
})
export class HotComponent implements OnInit {
posts: Post[] = [];
shownPosts: Post[] = [];
normalDrawerShown: boolean = true;
subscription!: Subscription;
...
constructor(private postService: PostService, private uiService: UiService) {
this.subscription = this.uiService
.onToggleNormalDrawer()
.subscribe((value) => (this.normalDrawerShown = value));
console.log("In constructor, this.posts.length: "+ this.posts.length);
}
ngOnInit(): void {
this.postService.getPosts().subscribe((posts) => (this.posts = posts));
console.log("In ngOnInit, this.posts.length: "+ this.posts.length);
console.log("In ngOnInit, this.posts[0].title: " + this.posts[0].title);
}
checkPosts():void{
console.log("In checkPosts, this.posts.length: "+ this.posts.length);
console.log("In checkPosts, this.posts[0].title: " + this.posts[0].title);
}
...
}
Post.ts:
export interface Post {
id?: number;
title: string;
fileName: string;
url: string;
section: string;
postTime: string;
upvotes: number;
downvotes: number;
comments: number;
}
post.service.ts:
getPosts():Observable<Post[]> {
return this.http.get<Post[]>(this.apiUrl);
}