The constructor in Angular 2 service is operational, however, other functions within the service are experiencing issues

Here is the code I've been working on:

This is the component.ts page code:

import {Component, OnInit, NgModule, VERSION} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import { UserService } from "../services/user.service";
import {Router, ActivatedRoute, Params  } from '@angular/router';

@Component({
       selector: 'app-all-users',
       templateUrl: './all-users.component.html',
       styleUrls: ['./all-users.component.css'],
       providers: [ UserService ]
 })

export class AllUsersComponent{
   users; usersnew; limit; limitnew;  

constructor(public userService: UserService, public router: Router,  public route: ActivatedRoute) {
  this.limit = "0";
  this.limitnew = "0";
  this.userService.getTestUsers(this.limit).subscribe(  users => this.users = users);
}
LoadMore(){  
  this.limit = "12";
  this.limitnew = +this.limitnew + +this.limit;
  this.userService.getTestUsers(this.limitnew).subscribe(  usersnew => this.usersnew = usersnew);
  this.users = [...this.users , ...this.usersnew];
  console.log(this.users);
  }
}

Now, let's take a look at the html page:

<div class="row">
  <div class="col-sm-3 *ngFor="let user of users ;let i = index ">
   <img *ngIf="user.image == ''"  src="http://localhost/assets/images/user.png"  class="user_img">
  </div>
</div>
<button (click)="LoadMore()"> Load More </button>

Lastly, the userService page code:

import { Component, Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map';
@Injectable()
export class UserService{
  constructor(private http: Http) { this.http = http; }

 getTestUsers(limitid): Observable<any> {        
     return this.http.get("http://localhost/AdminApp/api/get_all_user.php?id="+ limitid).map(res => res.json());
  }
 }

My query is regarding the behavior of the constructor in the component.ts page compared to the LoadMore function inside the userService.

Answer №1

Give this a shot:

class DisplayUsers {
    userList: Array<any> = [];
    updatedUserList: Array<any> = [];
    userLimit;
    newLimit;

    constructor(public userService: UserService, public router: Router, public route: ActivatedRoute) {
        this.userLimit = "0";
        this.newLimit = "0";
        this.userService.getAllUsers(this.userLimit).subscribe(users => this.userList = users);
    }

    ShowMore() {
        this.userLimit = "12";
        this.newLimit = +this.newLimit + +this.userLimit;
        this.userService.getAllUsers(this.newLimit)
            .subscribe((updatedUsers) => {
                this.updatedUserList = updatedUsers
            }, (err) => {
                console.log('An error occurred', err);
            }, () => {
                this.complete()
            });
    }

    complete() {
        this.userList = [...this.userList, ...this.updatedUserList];
        console.log(this.userList);
    }
}

Answer №2

To ensure efficient functionality, it is important to subscribe only once. Once subscribed, the function will continue to fire until the component is destroyed. To prevent this, remove the subscription from the LoadMore function.

Begin by importing the OnInit and OnDestroy lifecycle hooks from angular/core as shown below:

import { Component, OnInit, OnDestroy } from '@angular/core';

Next, within the component, create the subscription:

ngOnInit() {
    this.subscription = this.userService.getTestUsers(this.limit).subscribe(users => this.users = users);
}

Remember to unsubscribe when the component is destroyed:

ngOnDestroy(){
    this.subscription.unsubscribe();
}

Implementing these steps should enhance the functionality of your code. Good luck!

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

What could be causing my website to lose its responsiveness after linking a domain?

Recently, I created a basic website for an event in my town using AWS Amplify from Amazon. Initially, the website was hosted without a custom domain and had a random URL. It worked well on both web and mobile platforms. However, after connecting a custom d ...

Experiencing an issue with my Angular 6.1.0 setup, using angular-cli 7 and primeng 7 - specifically encountering the error message "Initializers are not allowed in ambient context."

Issue encountered in the primeng package: While examining node_modules/primeng/components/picklist/picklist.d.ts, errors were found at line numbers 65 and 66. I have investigated the primeng package further. primeng/components/picklist/picklist.d.ts l ...

Incorporating Copyleaks SDK into Angular: A Seamless Integration

Currently, I'm in the process of implementing the Copyleaks SDK with Angular to conduct plagiarism checks on two text area fields within an HTML form. Within the form, my goal is to incorporate two buttons: one to check for plagiarism on one text area ...

Sending an array of data using Angular in a web service

Here is my model object from model.ts name_id: string[]; public generateUrlencodedParameters(token: string, id?: number): string { let urlSearchParams = new URLSearchParams(); urlSearchParams.append('name_id', this.name_id.toS ...

Issue with the functionality of the material tree's parent node may not be operating

I created a material tree with the ability to select up to 42 elements. Once the limit is reached, the nodes become disabled. However, I encountered an issue where if some child nodes are selected while others are disabled due to reaching the limit, the pa ...

I'm seeing an issue where my SafeResourceUrl is being displayed as undefined within a function of the identical class

export class ClassName implements OnInit { url: string = "{{'content.url' | translate}}"; urlSafe: SafeResourceUrl; constructor(public sanitizer: DomSanitizer, private translate: TranslateService) { } ngOnInit() { ...

The parameter type 'router' cannot be replaced with the type 'typeof ...'. The 'param' property is not included in the type 'typeof'

I'm currently working on a node application using TypeScript and have set up routing in a separate file named 'route.ts' import home = require('../controller/homeController'); import express = require('express'); let ro ...

A guide on displaying a dynamically generated HTML string as HTML within an Angular 6 framework

I'm having trouble displaying Dynamic HTML (dropdowns) created with TypeScript. When I attempt to show it using innerHTML, the options appear as text instead of a dropdown menu. {{question.question}} <div [innerHTML]="question.question" c ...

Error when sending Angular 4 GET request with multiple Headers results in a 400 bad request code

I've been attempting to perform a POST request with headers in order to receive a response. The Angular code snippet I'm currently using for this request is shown below: const headers = new HttpHeaders({ 'Content-Type': 't ...

Is it possible to select a tab in Angular 10 Material Tabs based on a route parameter?

My webpage features a mat-tab-group, located at the URL /transactions. <mat-tab-group> <mat-tab label="Shipments"> <ng-template matTabContent> shipment content </ng-template> ...

Invoking a Components function from a Service in Angular may lead to a potential cyclic dependency issue

I am facing a challenge where I need to call a function from my filterComponent(component) within my engagementService(service). The function in my filterComponent accesses an array that is located within the engagementService. It uses the data from this ...

Transfer a file to Laravel using $request->input()

Is there a way to upload my file to FTP when I'm sending the data from Angular using JSON format instead of using $request->file("Fichier1") in Laravel? Here is an example of how the data is sent from Angular to Laravel: https://i.stack. ...

What is the procedure for linking my SQL database with Angular?

This is a sample HTML code snippet to create a sign-in form: <div class="col-md-8"> <form (submit)="onSubmit()" method="POST"> <input type="text" class="form-control mb-2" name="names" [(ngModel)]="profileForm.name" placeholder="Usern ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

Unresolved issue with RxJS - Finalize not triggering

When attempting a logout request, I have encountered an issue where the same actions need to be dispatched regardless of whether the request is successful or fails. My initial plan was to utilize the finalize() operator for this purpose. Unfortunately, I ...

Encountering a "property does not exist" error while using VS Code TypeScript within a Vue.js project

I am working on a Vuejs project in Typescript. The project compiles and runs perfectly without any errors. However, I am facing an issue with the TS linter. In my individual component files, I am using the component decorator as shown below: //videocard.c ...

Typescript error points out that the property is not present on the specified type

Note! The issue has been somewhat resolved by using "theme: any" in the code below, but I am seeking a more effective solution. My front-end setup consists of React (v17.0.2) with material-ui (v5.0.0), and I keep encountering this error: The 'palet ...

Preventing Event Propagation in Angular HTML

I am encountering an issue with stopPropagation, and I need assistance with implementing it in HTML and TypeScript for Angular. The problem is that the dialog opens but also triggers a propagation. Below is my code snippet in HTML: <label for="tab-two ...

Exciting new venture utilizing Angular version 15 in combination with the latest Firebase 9

Recently, I set up node version 18.10.0 and attempted to start a fresh Angular 15 project using Firebase 9 for hosting, Firestore database, and authentication. However, after running the commands below, I noticed that the @angular/fire directory was missin ...

Obtain varied results from the Knockout module

In my application, I am utilizing Knockout and Typescript. One of the classes in my code is as follows: class Address { State :string; ZIP: string; Street: string; } I want to create a component that will handle the updating of an object of ...