When delving into an object to filter it in Angular 11, results may vary as sometimes it functions correctly while other times

Currently, I am working on implementing a friend logic within my codebase. For instance, two users should be able to become friends with each other. User 1 sends a friend request to User 2 and once accepted, User 2 is notified that someone has added them as a friend. However, when I check if they are friends by iterating from User 1 to User 2, sometimes it works correctly and other times it does not. The issue arises when, even though I am friends with someone, the system prompts me to 'Add as Friend' again, which is undesirable. Interestingly, sometimes a simple page reload fixes this problem. Please note that 'this.data.user' represents the ID of the friend.

I suspect the problem lies in how I handle the request to retrieve all friends, causing this inconsistency.

Below is the snippet of code responsible for checking if users are friends or not, executed within the 'ngOnInit' lifecycle hook.


checkFriend: User[] = [];

if (success[1]) {
    this.data = success[0];
    this.checkFriends(this.data.user);
} else {
    this.modelDataService.getUserModel(this.outsideUserId).subscribe((t: Model) => {
        this.data = t;
        this.loadActiveUserConnections(this.data.user);
        this.checkFriends(this.data.user);
    });
}

this.modelDataService.getOutsideModel(this.outsideUserId).subscribe((t: Model) => {
    this.data = t;
    this.loadActiveUserConnections(this.data.user);
    this.checkFriends(this.data.user);
}); // The issue might arise here due to both being called from outside

checkFriends(id) {
    this.friendService.getAllFriendRequests().subscribe((finalRequesters) => {
        this.checkFriend = finalRequesters;
        this.checkFriend.forEach((oneRequest: any) => {
            console.log(oneRequest);
            if ((oneRequest.friendId === id || oneRequest.friendId === id) && oneRequest.status === "You are friend") {
                oneRequest.isFriend = true;
                this.isFriend = true;
            } else if (oneRequest.friendId === id && oneRequest.status === "Request Pending") {
                oneRequest.uniqueId = oneRequest.userId;
                oneRequest.isRequest = true;
                this.isRequest = true;
            } else {
                this.isFriend = false;
                this.isRequest = false;
            }
        });
    });

}

The following section presents the HTML code:


<a class="px-1" *ngIf="!checkUser">
  <button class="px-3 font-weight-600 btn btn-light" (click)="addFriend()" *ngIf="!isFriend && !isRequest">
    <span class="bi bi-person-plus-fill d-flex align-items-center">
      <span class="pl-2">Add Contact</span>
    </span>
  </button>
  <button class="px-3 font-weight-600 btn btn-light" *ngIf="isRequest">
    <span class="bi bi-person-plus-fill d-flex align-items-center">
      <span class="pl-2">Cancel Contact Request</span>
    </span>
  </button>
</a>

And here is the method for retrieving all friend requests:


getAllFriendRequests() {
  return this.http.get<any[]>(this.apiBaseURL + "/friends");
}

This is what the 'oneRequest' object looks like:


{ 
  createdDate: "2021-03-20T22:24:54.512Z",
  friendId: "602e4c30e3346466703376ab",
  id: "605676360fb6b109209674be",
  status: "You are friend",
  userId: "5fbc1bc72ffec245c4bd7725",
  __v: 0,
  _id: "605676360fb6b109209674be",
  ...
}

'friendId' represents the friend's ID, while 'userId' stands for the authenticated user's ID. Despite this, when I attempt to log 'oneRequest', it returns the entire array instead of a single object.

Lastly, let’s take a look at the backend implementation:


async showUserCV(req, res) {
  ModelData.aggregate()
  let modelData = await ModelData.findOne({userUrl: req.params.id }).populate("user").exec();
  if (!modelData) {
      res.status(204).json({error: "No Data"});
      return;
  }
  return res.status(200).send(modelData);
},

const ModelData = require("../models/data");

Answer №1

When seeking to repeatedly replace the data, consider utilizing map() in place of forEach(). Give this a shot:

this.checkFriend.map((oneRequest: any) => {
  // Insert your desired loop actions here
}

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

Enriching Angular Tables with Custom Buttons and Actions using ng2-smart-table

I am struggling to customize the button styles in ng2-smart-table. I have tried changing the code following the steps provided in the link below, but the buttons are still not appearing as desired. Specifically, I want to update the "Edit", "Delete", "Canc ...

Router navigation does not trigger LifeCycle calls

I currently have the following routes set up: {path:'home', component:HomeComponent, canActivate: [AuthGuard]}, {path:'profile', component:UserProfileComponent, canActivate: [AuthGuard] }, Additionally, in my navbar.component, I hav ...

socket.io / settings when establishing a connection

I'm facing an issue in my node.js / Express.js app where I need to pass parameters with the socket.io connection (saw a solution in another post). On the client side, here is a snippet of my code: edit var socket = io.connect('/image/change&ap ...

Issue with displaying jqplot in a jQuery page

Currently, I'm utilizing jqmobile pages for switching between various pages in an html5 application. One of these pages features a jqplot chart. Below is the code snippet: <div data-role="page" id="page-two" data-title="Page 2"> &l ...

Give properties to a function that is being spread inside an object

While working with React, I am facing a challenge of passing props from the instanced component into the mockFn function. The code example below is extracted and incorporates Material UI, but I am struggling on how to structure it in order to have access t ...

Establishing a connection to a remote Mongo database using Node.js

I have a remote MongoDB server and I am looking to establish a connection with it using Node.js. I was able to successfully connect directly with the Mongo shell, but for some reason, I cannot establish a connection to the MongoDB server in Node.js. The co ...

Display a specific paragraph inside a div using jQuery

I am having trouble getting my jQuery code to display a specific paragraph when a particular div is clicked on. My goal is for the content "v" to be displayed if the user clicks on the ".Virus" div, and for the contents of ".screenInfo" to be shown if the ...

Oops! Looks like the 'opennebula' module is missing in your Meteor.JS project

I've attempted using meteorhacks:npm but encountered the same issues. While working on a Meteor.JS application with iron:router installed, I'm facing difficulties loading the NPM module "opennebula" (found at https://github.com/OpenNebula/addon- ...

Angular 10: Display a notification when all checkboxes have been ticked

I am currently working on a project that involves Angular 10. The initial requirement was as follows: Users are presented with a list from which they need to choose one option using radio buttons. For example: the user selects covid19 from the given lis ...

Activate the zoom feature in jquery mobile

I am looking to implement the standard zooming effect in jquery mobile for my iOS iPhone app using jqm 1.3.2. After attempting the following: <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-s ...

Application with menu design, similar to the layout of google.com on mobile devices

Have you seen the Android smartphone with Chrome from GOOGLE.COM? Did you notice the pop-up MENU that looks similar to an application? This menu has a "SPRING" effect, and I'm curious how Google achieved this result. I tried using the property "-web ...

Steer clear of wrapping ng-repeat in nested indexes for routing purposes

I am currently working on an Angular application that displays data in 3 item columns using Bootstrap. To achieve this layout, I have implemented the following code snippet to group my array of data into sets of 3: examples.success(function(data) { $sc ...

Ways to obtain the file path of the compiled worker.js loaded from the worker loader, along with its hash

Currently, I am working on a TypeScript React application that utilizes Babel and Webpack for compilation. I have implemented a rule to load my worker with the following configuration: config.module.rules.unshift({ test: /gif\.worker\.js$/, ...

Class variable remains unchanged following AJAX request

Upon completion of the ajax request, two integers are received - this.N and this.M. However, these values are not being set by the storeDims() function even though the correct decoding is done on the dims variable. This implies that I am unable to access ...

Emberjs promises are enhanced with a filtering feature

My goal is to develop a search functionality using a JSON API. After following tutorials and successfully implementing it with provided examples: export default Ember.ArrayController.extend({ searchText: null, searchResults: function(){ ...

Exploring Angular.js: How to propagate model changes from a child controller within an ng-repeat loop?

I'm facing an issue in my Angular application where changes made to data inside a child controller's form are not being reflected back in the parent array after saving using Restangular. I have tried using debounce to auto-save the data, but it s ...

Problem with Ext.net TabPanel

I am encountering a problem with the Ext.net TabPanel. Every time the page containing the tab panel is opened for the first time after the application has been rebuilt, it throws an error Uncaught TypeError: Object [object Object] has no method 'getCo ...

The script fails to start using npm start, however, it runs smoothly when using node server.js

For a while now, I've been facing an issue that I just can't seem to resolve. When I navigate to my project's src folder and execute `node server.js`, everything functions as expected. I can access the application at http://localhost:3000/cl ...

Custom type checker that validates whether all properties of a generic object are not null or undefined

In an attempt to create a user-defined type guard function for a specific use-case, I am faced with a challenge: There are over 100 TypeScript functions, each requiring an options object. These functions utilize only certain properties from the object wh ...

Error: react/js encountered an unexpected token

While attempting to execute my project, I encountered an error in the console related to a function within the code. The exact error message reads as follows: "63:25 error Parsing error: Unexpected token, expected (function toggleDrawer = (open) => () => ...