Issue with editing images on the Angular front-end platform

Currently, I am developing a web application where I can input user information such as name, last name, age, birth date, and a picture. After creating a user, I should be able to delete or edit their details. However, I encountered an issue when updating a user's picture – instead of replacing the existing picture, a new user is being created with the modified image.

You can access the project on StackBlitz using this link: https://stackblitz.com/~/github.com/simeonskiq/Angular-project

edit-user.component.ts :

// Code for the EditUserComponent TypeScript file
// Includes form handling, user updates, and file upload functionality
// Problem: Updating user picture creates a new user instead of modifying existing one

user.service.ts :

// Code for the UserService TypeScript file
// Manages user data, including adding, updating, and deleting users
// Issue: Updating user picture results in creation of new user instead of updating existing one

I have tried various solutions without success. My goal is to successfully update a user's picture without creating a duplicate user.

Answer №1

Within the add-user component, you have implemented code that assigns an event listener to the confirmation modal button to trigger this.confirmAddUserAndNavigate():

  ngAfterViewInit(): void {
    const confirmModalElement = document.getElementById('confirmModal');
    if (confirmModalElement) {
      const saveButton = confirmModalElement.querySelector('.btn-primary');
      if (saveButton) {
        saveButton.addEventListener('click', () => {
          this.confirmAddUserAndNavigate();
        });
      }
    }
  }

However, there is already an existing function bound to the click event in the HTML template. Consequently, this results in double calls to addUser() whenever the button is clicked.

<div class="modal-footer">
   <button type="button" class="btn btn-secondary" (click)="cancel()">Cancel</button>
   <button type="button" class="btn btn-primary" (click)="confirmAddUserAndNavigate()">Save</button>
</div>

Answer №2

Here are the issues I identified in your code snippet.

  1. Make sure to always have a value inside the return of the of statement, otherwise the subscribe block won't execute.

Service

updateUser(updatedUser: User): Observable<null> {
  const index = this.users.findIndex(user => user.id === updatedUser.id);
  if (index !== -1) {
      this.users[index] = { ...this.users[index], ...updatedUser };  // Merge existing user data with updated data
  } else {
      console.error('User not found, cannot update');
  }
  return of(null);
}
  1. There is unnecessary code in the ngAfterViewInit method. Using event bindings is sufficient in Angular applications, so the addEventListener is not needed. I have commented out this code for you.

Add User Component

ngAfterViewInit(): void {
  // const confirmModalElement = document.getElementById('confirmModal');
  // if (confirmModalElement) {
  //   const saveButton = confirmModalElement.querySelector('.btn-primary');
  //   if (saveButton) {
  //     saveButton.addEventListener('click', () => {
  //       this.confirmAddUserAndNavigate();
  //     });
  //   }
  // }
}

If you are satisfied with the changes, please proceed with creating a pull request and merging the code. Additionally, I have included a .gitignore file in my latest commit for your reference.

Explore the Github Repository

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

Display errors on form fields upon form load using Angular schema form

Having an issue with Angular Schema Form where required attributes are missing when trying to load the form. The missing properties aren't indicated until editing and then removing content from a field. Hoping to find a solution for highlighting missi ...

Sending data from an Angular 2 application to a Spring MVC Rest API using HTTP POST method

I'm encountering an issue while attempting to perform an angular 2 http post JSON with multiple attributes to Spring MVC using @RequestParam. Despite my efforts of searching for a solution, I have not been successful in binding it to my object. I even ...

Utilize NodeJS and Typescript to input data into a postgreSQL database

Here is my code snippet: signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => { const username = req.body.username; const password = req.body.password; const age = req.body.age; const email = req ...

I can see the JSON data printing to the console in Ionic 3, but it doesn't display on

I seem to be facing a challenge with passing the 'item' to my search function in my Ionic 3 app. Although I was able to successfully connect to a json data file and print objects to the console, I am encountering an error message on the page that ...

What is the best way to find a specific field within an array of objects using Ionic/AngularJS?

I have an inquiry regarding Ionic/AngularJs: I am facing an issue with two searches on an object which are not functioning correctly. The first if (cartObj.cart.find (id)! = - 1) { ---> This is working fine. The second one is an if (cartObj.cart.findv ...

Determining the name of the currently focused DOM element in Angular2

How can I detect the name of a selected element from a group of select elements on a page? For example: <select (click)="functionDetectName()" name="test1"> <select (click)="functionDetectName()" name="test2"> <select (click)="functionDete ...

Is it necessary to verify the apiKey or does the authentication of the user suffice for an HTTPS callable function?

I'm interested in creating a cloud function that can be executed from both the client and the backend. After exploring the documentation, I learned that an HTTPS callable function will automatically include user authentication data, accessible through ...

manipulator route in Nest.js

I have the following PATCH request: http://localhost:3000/tasks/566-344334-3321/status. The handler for this request is written as: @Patch('/:id/status') updateTaskStatus() { // implementation here return "got through"; } I am struggling t ...

Using import statement is mandatory when loading ES Module in TS Node: server/src/index.ts

Attempting to kickstart a TypeScript Node project, I've gone ahead and added some essential dependencies (TypeScript, ESLint, Mongoose, and GraphQL). However, upon executing the command: ts-node-dev --respawn --transpile-only src/index.ts An error me ...

Is there a way to send a Razor boolean variable to an Angular directive?

Within my cshtml file, I am working with a boolean variable. However, when attempting to pass this variable to my Angular directive, it is being received as "False" rather than "false". Even hardcoding it to be "false" in lowercase does not solve the issue ...

methods for extracting JSON key values using an identifier

Is it possible to extract the Type based on both the file number and file volume number? [ { ApplicantPartySiteNumber: "60229", ManufacturerPartySiteNumber: "1095651", FileVolumeNumber: "E312534.2", Type: "Manufacturer", FileNumber ...

What is the Angular alternative to control.disable when working with a QueryList?

I have encountered a challenge in my Angular form where I need to disable certain fields. The issue arises from the fact that many of the HTML tags used are customized, making it difficult to simply use the disabled attribute. To address this, I have opted ...

Issues encountered with incorporating 'angular-route' or even 'angular-ui-router'

When I use 'angular-route' for routing and include the 'ngRoute' module in the dependent modules list, an error occurs: Error:- Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=MyApp&p1 ...

Make the current tab the active tab with the help of AngularJS

I have a set of five tabs that are functioning correctly. However, when I refresh the page, the active tab reverts back to its default state instead of staying in its current active state. Can anyone help me identify where I may be making a mistake? Here ...

What to do when encountering error TS2339: Property 'tz' is not found on type 'Moment'?

Within my Rails application, I have developed a frontend app utilizing angular. In this setup, I am incorporating both moment and moment-timezone as shown below: "moment": "^2.22.2", "moment-timezone": "^0.5.23", Fo ...

Transform a string into a boolean value for a checkbox

When using v-model to show checked or unchecked checkboxes, the following code is being utilized: <template v-for="(item, index) in myFields"> <v-checkbox v-model="myArray[item.code]" :label="item.name" ...

Troubleshooting: Problems with AngularJS $http.get functionality not functioning as expected

I have a user list that I need to display. Each user has unread messages and has not created a meal list yet. I want to make two http.get requests within the main http.get request to retrieve the necessary information, but I am facing an issue with asynchr ...

Determine the index of a specific character within a string using a "for of" loop

How can I obtain the position of a character in a string when it has been separated programmatically using a for...of loop? For instance, if I wish to display the position of each character in a string with the following loop: for (let c of myString) { ...

Material 3 Web Components definitions for SolidJS

Struggling with integrating the official Material 3 Web Components into SolidJS. Visit this link for more information. The main hurdle has been encountering typescript errors despite being able to see the components on the page. In my index.tsx, I'v ...

Transfer highlighted checkboxes between two containers. Any deselected checkboxes in the second container should also be removed from the initial container

I have successfully populated the necessary checkboxes within a single div element. Furthermore, I have been able to save the selected checkboxes to an object. https://i.sstatic.net/Pn0pu.png I am interested in learning how to display this object (check ...