Keep verifying the boolean value repeatedly

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);
  }
}

Answer №1

One issue to address is the failure to update the reload value to false after processing it. Please review the post.component.ts file for this particular code snippet related to subscribing to reload.

Snippet from post.component.ts to handle reload

   this.data.getValue().subscribe((value) => {
      if(value){
        this.data.getPostData().subscribe(data =>
          {
            this.posts.push(data);
            this.received='success';
          },
          error =>
          {
            this.received='error';
          });
          this.data.setValue(false);
       }
   });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on making jQuery color variables?

Is there a way to achieve CSS variable-like functionality with jQuery? For example, creating reusable CSS attributes in jQuery instead of using SASS variables. Imagine if I could define a variable for the color black like this: I want to make a variable t ...

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

"Encountering an error in Vue3 CompositionAPI: 'quizz is not defined' while trying to call a function from the

When attempting to call a function, I am encountering an error that says "Uncaught ReferenceError: quizz is not defined." <script setup> import { defineProps } from "vue"; import { useRouter } from "vue-router"; const router = us ...

Troubleshooting the issues with implementing cross-browser jscrollpane functionality

Hey there! I've been exploring this tool to customize the default scroll-bar, and here's a fiddle showcasing my experimentation. In the fiddle, I've included the following code snippet <div class="scroll-pane horizontal-only">(located ...

Unable to retrieve headers from extended Express.Request type

Currently, I am attempting to enhance the Request in Express so that it accurately represents the structure of a query. My current approach is as follows: export interface TypedRequestQuery<T> extends Express.Request { query: T; } While this met ...

Unique Symbols and Characters in JavaScript

My JavaScript code looks like this: confirm("You are selecting to start an Associate who is Pending Red (P RD) status. Is this your intent?") I am encountering a strange issue where I get an alert with special characters, even though my code does not con ...

Encountering issue with ngIf directive in Angular

In my Angular project, I am trying to display data from a variable that is formatted in json. I have successfully done this using *ngfor, but now I also want to add a condition where it checks if msg.who=="Bot". My current code looks like this: <div cl ...

What could be causing my bounce animation to begin 50 pixels higher than its intended starting point?

Trying to create a bouncing effect on text Check out my attempt here. It seems like the bug is in this area. @keyframes bounce{ 0%, 40%{ transform:scale(2,.5) translate(0,100px); } 45%,55%{ transform:translate(0,-50px); } 55%, 100%{ ...

Steps to simulate a TouchEvent programmatically using TypeScript

Is there a way to manually trigger the touch event in TypeScript? In JavaScript, it was possible but I am struggling to achieve the same in TypeScript. For example: let touchStart: TouchEvent = document.createEvent('TouchEvent'); touchStart.i ...

Exploring ElectronJs: The journey to sending messages from ipcMain to IpcRender and awaiting a response

I need help with sending a message to ask the renderer to parse an HTML string mainWindow.webContents.send('parse html', { resp}) The renderer processes the data and sends a reply ipc.on('parse html',function(e,p){ let b ...

Building a node.is script to validate email addresses

This code snippet is for validating email addresses. I have successfully implemented example 5, where the email length must be over 5 characters to avoid errors and prompt users to re-enter their email address. However, I am unsure how to handle examples ...

Koajs functions yield their return values

When working with expressjs, I typically utilize asynchronous functions as shown below: function foo(callback) { var bar = {a: 1, b: 2}; callback(null, bar); } foo(function(err, result) { // result is {a: 1, b: 2} }); In Koajs, I use the yield wit ...

What could be causing AngularJS to truncate my URL in the search bar?

Currently, I am in the process of setting up a state provider for a CRUD website. One issue I encountered is that when I navigate to www.mysite.com/posts/mypost, the URL gets shortened to www.mysite.com/mypost and does not trigger the controller as intend ...

Issues with jQuery not detecting click events

Here is an example of HTML: <div class="sortable-buttons"> <ul> <li><a>Recent</a></li> <li><a>Popular</a></li> <li><a>Being Discussed</a></li> </ul> </div ...

Enhance the functionality of selectize.js by incorporating select options through ajax

I'm currently working on implementing options to a select box using AJAX and selectize.js. When not using selectize.js, everything functions correctly. The two select boxes are interconnected so that when one is updated, the values in the other select ...

A guide on efficiently incorporating a php variable into json format, then transferring it to ajax

My Sample Code var ajaxResponse = xmlhttp.responseText; //ajax response from my php file jsonData = JSON.parse(ajaxResponse); alert(jsonData.result); And in my PHP Script $resultValue = 'Hello'; echo '{ "result":"' . $result ...

Issue - The path to the 'fs' module cannot be resolved in ./node_modules/busboy/lib/main.js

After adding a new React component to my NextJS app, I encountered a mysterious error in my local development environment: wait - compiling... error - ./node_modules/busboy/lib/main.js:1:0 Module not found: Can't resolve 'fs' null Interest ...

Is it accurate to categorize every ajax request (using xmlhttprequest) as a web service request?

Recently, I began incorporating AngularJS with Spring MVC as my backend. I have been utilizing $resource to connect with my backend. Given that this is a restful service and $resource operates using ajax, I find myself questioning: 1) Is ajax solely used ...

A guide to incorporating nested loops with the map method in React JS

I've come across numerous threads addressing the nested loop using map in React JS issue, but I'm still struggling to implement it in my code. Despite multiple attempts, I keep encountering errors. Here are some topics I've explored but cou ...

Switch out the HTML content within the JavaScript include

Here is the situation: <script type="text/javascript" src="http://xy.com/something.js"></script> This code snippet in my PHP/HTML file loads the entire something.js file. Inside that file, there are lines containing "document.write..." which ...