Discovering the index of an item in Angular

My delete function emits socket.io to update the other party's items list and remove the specific item. The issue arises when I receive the socket data as I struggle to find the matching item to update it.

Logic

  1. User 1 deletes a message
  2. User 2 receives a notification saying "this message was deleted"

Flow

  1. User 1 deletes the message (works)
  2. The message is successfully deleted for User 1 (works)
  3. socket.io is informed of the deletion (works)
  4. User 2 receives the deleted message data from socket.io (works)
  5. socket.io attempts to find and replace the deleted message (not successful)

Code

User 1 deletes the message

async presentPopover(ev: any, indexOfelement: any, own: any) {

    // send clicked item data to popover (popover will delete it and send back results)
    const popover = await this.popoverController.create({
      component: MessagesComponent,
      cssClass: 'my-custom-class',
      event: ev,
      componentProps: { id: ev, index: indexOfelement, from: 'pchat', own },
      translucent: true
    });

    // returned results from the popover
    popover.onDidDismiss().then((result: object) => {
      console.log('res2021 1: ', result);
      console.log('this.room.messages 2: ', this.room.messages);
      if (result['data']) {
          this.socket.emit('messageDelete', { message: result['data'] }); // data is "id: 187, index: 15"
          this.room.messages.splice(result['data'].index, 1); // remove message from user 1 list (preferably replace the text here instead of solely removing it)
      }
    });
    return await popover.present();
}

(popover)

// delete message (in the popover)
Pdelete(event) {
    this.privateChatsService.deleteMessage(this.navParams.get('id')).subscribe((res: any) => {
        this.popoverController.dismiss({ id: this.navParams.get('id'), index: this.navParams.get('index') }); //send back the data
    });
}

User 2 receives an update about the deleted message

ngOnInit() {
    // remove the deleted message
    this.socket.fromEvent('messDel').subscribe((message: any) => {
        console.log('from del emit in private chat: ', message); // data is "id: 187, index: 15"
        this.room.messages.splice(message.msg.message.index, 1); // make changes in the deleted item ("index" cannot be found)
    });
    // end of socket.io
}

Note: The issue lies in the

this.room.messages.splice(message.msg.message.index, 1);
code where the socket struggles to locate the correct item based on the index whereas the rest works smoothly.

Answer №1

Issue Resolved

In relation to the matter discussed,

this.room.messages.splice(result['data'].index, 1); // remove message from user 1 list (prefered if replace the text as well here instead of removing it)

To address this, I have made modifications to my response from the popover feature in order to update the list items rather than deleting them.

Pdelete(event) {
    this.privateChatsService.deleteMessage(this.navParams.get('id')).subscribe((res: any) => {
      this.popoverController.dismiss({ id: this.navParams.get('id'), index: this.navParams.get('index'), deleted_at: res.data.deleted_at });
    });
  }

The inclusion of deleted_at is crucial for displaying placeholder text in HTML.

I have also adjusted my socket listener as follows to accurately identify and update the correct item:

this.socket.fromEvent('messDel').subscribe((message: any) => {
      this.room.messages.find(item => item.id == message.msg.message.id).deleted_at = message.msg.message.deleted_at;
});

Furthermore, for the deletion action initiated by User 1, I have implemented similar logic in the socket listener to display placeholder text instead of completely removing the message from their list.

// retrieved data from the popover
popover.onDidDismiss().then((result: object) => {
      if (result['data']) {
        this.socket.emit('messageDelete', { message: result['data'] });
        this.room.messages.find(item => item.id == result['data'].id).deleted_at = result['data'].deleted_at;
      }
});

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

Dealing with NULL values in a Postgresql database

In the web-survey I created, users are able to select their answers by using radio buttons. To determine which buttons have been selected, I utilize javascript. I have not pre-set any default states for the buttons, allowing users to potentially leave ques ...

Can a graph effectively showcase data across a sporadically ordered timeline?

I have a collection of data stored in a database. While I have come across jpgraph during my research, I found that it may not be ideal for handling random time-sequencing and I am not a fan of their gantt chart layout. Do you have any recommendations for ...

One div on Chrome for Mac is experiencing an issue with applying the background image

I currently have a website hosted on GitHub pages at this link: When viewing the site on Windows Chrome, the bottom div containing the filtering buttons blends seamlessly with the dark grey background set in the wrapper div. However, when viewed on Mac Ch ...

Why isn't the onChange function triggering in the input type text when the input is not manually typed in?

I am currently facing an issue with two text fields in my HTML form. Here is how they are set up: HTML : <input type="text" id="input1" onchange="doSomething();" disabled/> <input type="text" id="input2"/> JavaScript : function doSomething( ...

Do we need to wait a considerable amount of time for an asynchronous function to run in a request?

I have a specific request that I need to address. The first snippet of code shows a function called handleUpdate1 which uses async/await to run a function named _asyncFuncWillRun10Minutes, causing the client to wait approximately 10 minutes for a response ...

AngularJS UI Router: Best Practices for Including the Controller Script

I have created a basic AngularJS single page application that uses UI Router to navigate between two views. When the user clicks on the Home link, they should see a line of text. Similarly, clicking on the About link should display some text as well, but i ...

Creating dynamic links within HTML through real-time updating

In my application, I have a feature that generates a list of words and converts them into clickable links. When the user clicks on a link, I want to extract the {{word.name}} from the HTML link without navigating to a new page. I simply need to retrieve th ...

What purpose does the class serve in typescript?

This is a unique version of app.component.ts in the Angular Tour of Hero tutorial. import { Component } from '@angular/core'; export class Superhero{ name : string; id : number; } const SUPERHEROES : Superhero[] = [ {name : 'Wonder ...

At which point during the lifecycle of an Angular application should the JWT token be refreshed

As a new Angular user, I am uncertain about where to refresh an access token. I am familiar with guards and interceptors, but I need guidance on the best approach and any potential trade-offs. Many tutorials cover the "how" but lack insights into the "why" ...

What steps should be taken to effectively integrate Amplify Authenticator, Vue2, and Vite?

Embarked on a fresh Vue2 project with Vite as the build tool. My aim is to enforce user login through Cognito using Amplify. However, when I execute npm run dev, I encounter the following issue: VITE v3.1.3 ready in 405 ms ➜ Local: http://127.0.0 ...

Using a Material-UI component to activate a React Router Link

Currently, I am facing an issue while using material-ui components in react with react-router. The problem arises when I try to display list-items that double up as link elements but also have a submenu inside which should not activate the parent link. Unf ...

Jquery divides large array into multiple new callbacks during parsing

Encountered a small issue where a JSON response contains a byte array with 67615 entries. Occasionally, it inserts `[....,154,156,);jQuery1910039778258679286416_1363006432850(181,104,...] every ~7300 characters When attempting to parse it using the usua ...

Axios promise handler in Vue Js is limited to processing only a single statement at a time

I'm currently utilizing Vue Js in my Laravel project to execute a POST request. Everything seems to be functioning properly, but I'm encountering some issues while dealing with the promise: axios.post('/customer/update',this.custo ...

"When running next build, NextJS fetch() function throws an error indicating an invalid URL, but everything works fine when using

Currently, I am in the process of developing a NextJS React application and attempting to retrieve data from my server by using the following line of code: let data = await fetch('/api/getAllAlumniInfoList').then(res => res.json()) Interestin ...

Get a new perspective from a different page's refresh

I have a unique situation where I am working on a project that involves two separate pages, each displayed on different computers. What I hope to achieve is that when I click a button on the first page, it triggers a refresh of the second page. Is there a ...

jquery-validation error in gulp automations

I've encountered a sudden error in my gulp build related to jQuery validation. There haven't been any recent changes that would trigger this issue. Interestingly, one of my colleagues is experiencing the same problem, while another one is not. We ...

Remove any repeated elements from the array and ensure that the element which occurs the most is placed at the beginning of the new array

Given an array "source" with values [2, 9, 9, 1, 6], we use the filter method to remove duplicate elements. The variable 'ans' stores the result. Now, how can we rearrange the elements in such a way that the highest repeated value (9) comes firs ...

Real-time Exchange of HTML Data Forms

Hey everyone, I am completely new to programming and I would really appreciate your guidance through this process. Let's imagine a scenario where two users need to communicate through HTML forms. The first user fills out an HTML form (first name, la ...

Angular 6's observable variable doesn't properly support Ng If functionality

I successfully implemented server-side pagination in the Angular6 material data grid following the instructions from this link. Now, I am facing an issue where I want to display a "No Data Found" message if the response dataset is empty. I tried using ngI ...

DomSanitizer in Angular is not able to bind to an Angular component

Trying to dynamically insert HTML content into a DIV has been successful when done statically. The following code is functioning properly: <popover-content #pop1 title="Cool Popover" placement="right" ...