Issue with for loop execution within subscribe event

In my chat design, there is a list of people on the left side. When a user clicks on any person, I display their chat history on the right side. To achieve this, I need to transfer user details from one component to another using an RXJS subscribe call. Data transfer is successful, but I encounter an issue after receiving user details through the subscribe call in the right component. I make an API call to fetch users' chat history and display chats in that component. However, when I try to run a for loop in the success response of the API, it does not execute. Below is the code of my right side component:

` ngOnInit() {

    this.userProfileId = this.utilService.getCurrentLoginUserProfileId();
    if (this.userProfileId) {

      this.friendId = this.userDetail.userProfileId;
       // get users data
      this.utilService.onChangeUserDetailData.subscribe(data => {
      console.log('data', data);
      if (data) {
        this.userDetail = data;
        this.friendId = this.userDetail.userProfileId;
        this.sendUserOnlineSocket(data);


        // get chat history api
        this.getUsersChatData(data);
        }
    });

    }

// get users chat data
  getUsersChatData(user: any) {
    let postObj;
    if (user.chatRoomId) {
      postObj = {
        from_user: this.userProfileId,
        to_user: user.chatRoomId
      };
    } else if (user.userProfileId) {
      postObj = {
        from_user: this.userProfileId,
        to_user: user.userProfileId
      };
    }

    this.chatPageService.getChatData(postObj).then((res: any) => {
      console.log(' chat data res', res);
      if (res['status'] === 200) {
        if (res['data']['length'] > 0) {
          for (let i = 0; i < res.data.length; i++) {
            console.log('message response', res[i]);
            if (res[i]['user_profile_id'] === this.userProfileId && res[i]['to_user_id'] === this.friendId) {
              this.messageData.push({ side: 'right side', data: res[i] });
            } else {
              this.messageData.push({ side: 'left side', data: res[i] });
            }
          }
          console.log('message data', this.messageData);
        }
        console.log('message data', this.messageData);
      }
      console.log('message data', this.messageData);
    }).catch(err => {
          if (err.hasOwnProperty('error')) {
            this.utilService.errorHandler(err.error);
          } else {
            this.utilService.showError(
              'Error',
              this.utilService.commonErrorMsg
            );
          }
    });
  }

`

I can see 'chat data res' in the console, however, the 'message response' inside the for loop returns undefined and the subsequent consoles are not executed. Can someone provide a solution or suggest an alternative approach for this issue?

Answer №1

It appears that there is a mistake in your code.

Instead of referencing res[i], be sure to use res.data[i]

for (let i = 0; i < res.data.length; i++) {
        console.log('message response', res.data[i]);             
 }

After making the above adjustment, replace instances of res[i]['user_profile_id'] with res.data[i]['user_profile_id']. Make this modification wherever necessary in your code.

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 on incorporating JavaScript variables within a GraphQL-tag mutation

I'm having trouble consistently using javascript variables inside graphql-tag queries and mutations when setting up an apollo server. Here's a specific issue I've encountered: gql` mutation SetDeviceFirebaseToken { SetDeviceFirebaseTok ...

Tips on injecting configuration into forRoot

Is there a method to inject configuration object into AppModule's forRoot() function? How can I access the configService if there is no constructor within the module? config.yml: smtp: host: 'smtp.host.com' port: 10 secure: true aut ...

What is the proper way to invoke the correct store 'collection' using ngrx-store?

I'm currently working on a sample app to learn ngrx and I have two different sets of data - one for counters and the other for URLs. Each store is displayed correctly in their respective components, and I can also increment & decrement the counter usi ...

What is the best way to showcase the information retrieved from my API?

I am attempting to display the ID and Document number that are retrieved from an array. Data Returned However, I am not seeing any results in return. You can view the application results here. I have tried using string interpolation like {{document.id}} ...

Combining and grouping objects by their IDs in a JavaScript array

Information: [ { "id": "ewq123", "name": "Joshua", "order": "Pizza" }, { "id": "ewq123", "name": "Joshua", "order": ...

Incorporate an external JS file (File A) that is dependent on another JS file (File B) into a TypeScript file within the context of Angular 4

Working on an Angular 4 project, I recently installed two external JS libraries using npm. They are now in the node_modules folder and usable in another TS file within my project. The issue arises because import B requires import A, preventing me from effe ...

Step-by-step guide on how to index timestamp type using Knex.js

I'm in the process of indexing the created_at and updated_at columns using knex js. However, when I try to use the index() function, I encounter the following error: Property 'index' does not exist on type 'void' await knex.sche ...

Bar chart in Highcharts vanishing following the update from version 10.2.1 to 10.3.1

I've been in the process of updating my highcharts to the latest version, but I've hit a roadblock. Specifically, I have a bar chart set up with the following configuration: { chart: { type: 'bar', ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

"Unexpected Type Inference Issue: A variable initially defined as a string inexplicably transforms into 'undefined'

Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to method from the library). In an intriguing scenario, the variable type shifts to string | undefined within a for..of loop, whereas outside of the loop ...

Auth.logout() callback in AngularFire 2

As I attempt to log out and then navigate to a login URL, I encounter an issue with the authguard preventing logged-in users from accessing it. Due to the asynchronous nature of the operation, clicking the method event twice seems to be necessary for it to ...

What is the significance of having nodejs installed in order to run typescript?

What is the reason behind needing Node.js installed before installing TypeScript if we transpile typescript into JavaScript using tsc and run our code in the browser, not locally? ...

Experience the power of React TypeScript where functions are passed as props, but access is restricted

Currently, I am working on creating a toggle button using react and typescript. In order to challenge myself, I have decided to pass a function as a prop to a child component to implement a complex feature. From what I remember, utilizing 'this.props& ...

Angular 13 ModuleWithProviders Bug: A Dilemma Worth Solving

After creating a module and adding a service provider to its forRoot() static method, I imported the module into my app.module.ts file and included it in the imports section as ZooModule.forRoot(). However, when I attempted to inject the service from the Z ...

Problem arises with connecting data in the relationship between a parent and child

Hi there, I am new to Angular 6 and currently encountering an issue with data binding. I have set up a test project with a parent-child relationship for data binding in the heading, but unfortunately, it's not working as expected. Can anyone lend me a ...

What is the best way to fetch the id of the option that has been chosen from a bootstrap drop-down menu?

I recently created a basic drop-down list like this: https://i.sstatic.net/4Tlxx.png Here is the HTML code for it: <select class="form-control" id='0' (change)="retrieveValue($event.target)"> <option id='0'>{{ g ...

Enhancing Luxon DateTime with extension type support

Referencing the issue at https://github.com/moment/luxon/issues/260, I am looking to extend the DateTime object as shown below: import { DateTime } from 'luxon'; function fromUnix(tsp?: number): DateTime { return DateTime.fromMillis(tsp * 1000 ...

Remove the JavaScript files from the distribution folder when removing TypeScript files in an Angular 2 project

I came across a solution that recommended separating Angular2 TypeScript files and JavaScript files into different folders like 'dist'. By following this, I moved my files to the 'app' and 'dist' folders. Interestingly, whenev ...

Is there a way in Angular2 to append a class name from a variable to the host element without removing the current classes?

I am facing a challenge where I have a class name stored in a variable and I need to apply it to the host element of my Angular2 component. However, I am struggling to find a solution for this. While I can easily add a constant string as a class using Hos ...

The base component is not updating the property from the inherited component

Working on an Angular project where I have a component that inherits from a base component. @Component({ selector: "my-baseclass-component", template: ` <div style="border:1px solid red;padding:10px"> Counter Value (Check Co ...