Unable to invoke function in Angular 4 after a delay of 3 seconds

Every time I attempt to call getUsersChats again to display a badge for new messages, the code seems to be working fine. However, I encounter an error that says:

 "ERROR TypeError: Cannot read property 'getUsersChat' of undefined"

getUsersChat function

 getUsersChat() {

    let clientsKeys: Array < any > ;

    let i = 0;
    // tslint:disable-next-line:prefer-const
    let key: any;

    this.mySegService.getChats().subscribe(res => {

      this.clientsShortList = new Array < any > ();
      clientsKeys = Object.keys(res);

      this.totalNumberClients += clientsKeys.length;

      clientsKeys.forEach(clientKey => {

        if (i < ++i && res[clientKey]['messages'] !== undefined ) {
          this.clientsShortList.push({
            name: res[clientKey]['name'],
          });
        }

        if (res[clientKey]['name'] === this.chatcheck ) {

          this.clientsShortList = new Array < any > ();
          this.clientsShortList.push({
            name: res[clientKey]['name'],
            number: this.compare
          });
        }
        this.clientsShortList.reverse();
        console.log(this.clientsShortList);

      });

    });
    this.newmessageNumber(this.clientsShortList);
  }

The issue arises in the setTimeout(() =>... part of the code. I'm unsure of what I'm doing wrong here, so any assistance would be greatly appreciated.

newmessageNumber(array: any) {
     // tslint:disable-next-line:no-shadowed-variable
     let element;
     let i = 0;

    for (let index = 0; index < array.length; index++) {
      element = array[index]['name'];
    }

    this.mySegService.getChatsLast().subscribe(res => {
       try {
        localStorage.setItem('user', res[0]['user']);
       } catch (error) {
        // nd
       }
       this.chatcheck = localStorage.getItem('user');
      // console.log(this.chatcheck);
       if (this.chatcheck === element ) {
            this.compare = '1';
      }
    });

    for ( i ; i < 3; i++) {

      (function(i) {
          setTimeout(() => {
            this.getUsersChat();
          }, 1000 * i);
      })(i);
  }


 }

If anyone can provide some guidance on resolving this issue, it would be much appreciated.

Answer №1

since the function getUsersChat is out of scope within the context of the setTimeout

you can maintain the scope by using the following approach.

newmessageNumber(array: any) {
     // tslint:disable-next-line:no-shadowed-variable
     let element;
     let i = 0;

    for (let index = 0; index < array.length; index++) {
      element = array[index]['name'];
    }

    this.mySegService.getChatsLast().subscribe(res => {
       try {
        localStorage.setItem('user', res[0]['user']);
       } catch (error) {
        // nd
       }
       this.chatcheck = localStorage.getItem('user');
      // console.log(this.chatcheck);
       if (this.chatcheck === element ) {
            this.compare = '1';
      }
    });
    var self=this;
    for ( i ; i < 3; i++) {

      (function(i) {
          setTimeout(() => {
            self.getUsersChat();
          }, 1000 * i);
      })(i);
  }


 }

Answer №2

solved by following these steps

 fetchUserChats() {

        let clientKeysArray: Array < any > ;

        let i = 0;
        // tslint:disable-next-line:prefer-const
        let key: any;
        // tslint:disable-next-line:no-shadowed-variable
        let element: any;

        this.mySegService.fetchChats().subscribe(response => {

          this.clientListShort = new Array < any > ();
          clientKeysArray = Object.keys(response);

          this.totalClientCount += clientKeysArray.length;

          clientKeysArray.forEach(clientKey => {

            if (i < ++i && response[clientKey]['messages'] !== undefined) {
              this.clientListShort.push({
                name: response[clientKey]['name'],
              });
            }


            if (response[clientKey]['name'] === this.chatIdentifier) {
              this.clientListShort = new Array < any > ();
              this.clientListShort.push({
                name: response[clientKey]['name'],
                number: '1'
              });
            }

            this.clientListShort.reverse();
            console.log(this.clientListShort);
          });

        });
        
        for (let index = 0; index < this.clientListShort.length; index++) {
          element = this.clientListShort[index]['name'];
        }

        this.mySegService.fetchLastChats().subscribe(res => {
          // console.log(res);
          try {
            localStorage.setItem('user', res[0]['user']);
          } catch (error) {
            // ignore
          }
          this.chatIdentifier = localStorage.getItem('user');
          console.log(this.chatIdentifier);
          if (this.chatIdentifier === element) {
            this.fetchUserChats(); 
          }

        });



}

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

A guide to applying ngClass to spans using ngFor according to the value stored in localStorage

When I try to add the active-span class to an element after selecting a size, it's easy to do with jQuery but I'm finding it a bit confusing when trying to achieve the same in Angular. The goal is to have the active-span class added when a size ( ...

Are MobX Observables interconnected with RxJS ones in any way?

Is the usage of RxJs observables in Angular comparable to that in React and MobX? I'm struggling to find information on this topic. ...

Halt of dispatcher playback occurs after a duration of 10 minutes with discord.js

Currently, I've been working on a music bot using discord.js. To handle audio streaming, I'm utilizing @discordjs/opus and ytdl-core-discord. Everything runs smoothly when testing the bot locally on my machine - songs from YouTube are played with ...

RangeError: The React application has surpassed the maximum stack size limit, causing an error to be thrown

Hey there, I could use a hand. I'm fairly new to React and attempting to develop an application for managing contacts by adding them to Local Storage and deleting them. Below is the code snippet from my App.js file: import React, {useState, useEffect} ...

What causes the disparity in functionality between simple html and css in an Angular 2 project compared to a vanilla html website?

When incorporating the following html/css into a new Angular project created with Angular CLI using 'ng new ProjectName', I encountered issues. Despite adding the CSS to app.component.css or styles.css and the HTML to app.component.html, the Angu ...

Exploring the versatility of Angular 4 by implementing a switch feature with

My goal is to have the menu change based on the click of the "Cadastros" action, but it seems like the issue lies with the "workspaceSelected" property not being visible to all components. I believe the best approach in this situation would be to have the ...

Managing a project with multiple tsconfig.json files: Best practices and strategies

I've got a project structured in the following way: \ |- built |- src |- perf |- tsconfig.json |- typings |- tsconfig.json My main tsconfig.json looks like this: "target": "es6", "outDir": "built", "rootDir": "./src", Now, I need to have a ...

What are some ways to streamline this repetitive angular code using promises?

As a newcomer to Angular development, I'm curious if there's a more elegant way to streamline the repetitive code shown below. addTransaccion() { try { if (this.idTransaccion === '0') { this.transaccionesSrv.addTransa ...

unable to expand navbar in Angular 5 project with Bootstrap 4

I am encountering an issue with my navigation bar in a project that uses Angular5 and Bootstrap4. The navigation bar is supposed to expand when the screen size is small, as indicated by the navbar-expand-sm class in Bootstrap4. However, the navbar remains ...

Don't forget to include the "NgxsSelectSnapshotModule" when importing the NGXS module

[UPDATE: Great news! We have discovered how to replicate the issue, check out the minimal reproduction] Description Our server logs are flooded with 2 FATAL Errors in both production and non-production environments: FATAL [main.js:xx] NgxsSelectSnapshotM ...

What is the best way to update the color of a label in a Mantine component?

When using the Mantine library, defining a checkbox is done like this: <Checkbox value="react" label="React"/> While it's possible to change the color of the checkbox itself, figuring out how to change the color of the label ...

Using TypeScript to patiently wait for an observable or promise to complete before returning an observable

As a newcomer to TypeScript & RxJS, my goal is to return an Observable once another Observable has completed: public myObservable = () : Observable<boolean> => { console.log('Retrieving the token from the database'); return ...

What methods are available to pass a variable value between two components in Angular 2?

I've been experimenting with Angular2 and recently created a component called appmenu using angular cli. The code in appmenu.html looks like this: <ul> <li (click)="menuitem1()">Menu Item 1</li> <li>Menu Item 2</li> ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

Guide on incorporating arrow buttons for navigation on the left and right sides within a Primeng tab view component in Angular 8

Looking to enhance navigation tabs with left and right arrows for better support of larger tab sizes in the nav menu. I attempted using Primeng since my Angular 8 application already utilizes this library. Are there any other libraries besides Angular Ma ...

The outcome of array.splice is null

Recently, I've delved into learning angular4 and typescript. If this seems like a simple question, bear with me. Within my angular service, I've defined a method: removePerson(person: Person): Promise<void> { return Promise.resolve( ...

Manipulating CSS styles through Javascript with passed parameters

I need a feature that allows users to pick the color of the buttons displayed on the website. Currently, I am working with Angular 6 and JavaScript to achieve this functionality. I am focusing on setting the primary color, affecting buttons with the Bootst ...

What methods can I use to create an RXJS stream that only updates the state once all sequential calls have been successful?

Currently, I am delving into rxjs within the realm of Angular. However, I am facing difficulties in merging these concepts to accurately portray the following scenario: I initiate an HTTP request to an endpoint, which returns some data This data is then u ...

Is the Angular custom validator failing to trigger if the input is left untouched?

My form setup is as follows: this.form = this.formBuilder.group({ name: ['', Validators.required], email: ['', this.customValidator()] }); I have a button labeled "submit" with a condition for disabling: <button [disabled]=" ...

The properties required for type 'Subscription' are not present

I encountered an issue in my IDE while trying to run the following code. Within my component, I am making a call to a service in the ngOnInit method to fetch some data. This service, in turn, calls another service to gather additional information before f ...