The issue of duplicate items being stored in an array arose when inserting a new element

I am new to angular and currently working on an application that allows users to take notes and store them in a database.

However, I have encountered a problem during the note addition process. When there are no existing notes in the database and I add two new notes, both notes appear the same on the user interface despite being different in the database.

https://i.sstatic.net/tXYd2.jpg

Upon further investigation, I noticed that the data retrieved from the database is in JSON format. After adding new data, the array of notes is displayed as -

0: {}
1: {}
2: Note{}
3: Note{}

NoteService -

export class NotesService {

  private baseURL = 'http://localhost:8082/api/v1/note';
  notes: Note[];
  notesSubject: BehaviorSubject<Note[]>;

  constructor(private http: HttpClient) {
    this.notes = [];
    this.notesSubject = new BehaviorSubject<Note[]>([]);
  }

  // More code follows here...

NoteTakerComponent : addNote() -

addNote(): void {
        // Code for adding notes goes here
      }

NoteTaker view -

<!-- Code for viewing and adding new notes -->

// HTML code for displaying the form to add notes.

NoteView Component -

// TypeScript code for displaying the added notes.

export class NoteViewComponent implements OnInit {
  // Code for retrieving and displaying notes goes here
}

The goal is to display newly added notes along with previously existing notes seamlessly.

Answer №1

An essential mistake occurred by modifying the same note object instead of creating a new one.

The NoteTaker component has been updated -

addNote(): void {
    this.errMessage = '';
    this.note = new Note();
    if (this.validateNote()) {
      this.note.noteCreatedBy = sessionStorage.getItem("userId");
      this.note.noteTitle = this.noteTitle;
      this.note.noteContent = this.noteContent;
      this.note.noteStatus = this.state;
      this.note.category = this.editCategory;
      this.note.reminder = this.editReminder;
      let maxId = 0;
      if (this.noteService.notes.length > 0) {
        this.noteService.notes.forEach(note => {
          if (note.noteId > maxId) {
            maxId = note.noteId;
          }
        });
      }
      this.note.noteId = ++maxId;
      this.noteService.addNote(this.note).subscribe(response => {
        this.noteService.notes.push(this.note);
        this.noteService.notesSubject.next(this.noteService.notes);
        console.log('note taker', this.noteService.notes);
        this.reset();
      },
        error => this.handleErrorResponse(error));
    }
  }

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

Express Router triggers XHR onreadystatechange 3

Having just started using Express, I am currently working on setting up a login authentication system. However, I have encountered an issue where XHR is not showing a ready state 4. This problem arose after implementing express.Router which I came across i ...

The dynamic links are not supported by Webpack when used with Angular2

The Challenge I am faced with the task of creating a reusable Angular2 component that can display a custom image and be utilized by multiple other components. The goal is to have the flexibility to customize the image being displayed by passing a variable ...

"Triggering a click event on the unordered list within an Angular 2

Looking to retrieve the class name when clicking on any item in a list. <ul id='color' name='color' class="choose-color" (click)=getColor()> <li class="color1"></li> <li class="color2"&g ...

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

Transform all Date fields in the Array to a standardized date format

I have an array with various fields, including a field called dateofbirth. I need to remove the time and change the format to MM-DD-YYYY. var records = [ { "recordno":"000001", "firstname":"Bo", "middlename":"G", "lastn ...

What are the ways to prolong or pause the JSON transformation process in NodeJS?

I'm currently extracting keywords using ExpressJS: /* * GET keywords. */ router.get('/keywords', function(req, res) { // Ensure user is logged in if (req.user) { var db = req.db; var user = req.user; db.col ...

What are the steps to connect to multiple databases with ExpressJS?

I have a server with 3 databases containing identical tables. The databases are named DB1, DB2, and DB3. When working with a specific database, I utilize the following code in app.js: var cnxDB = require('./routes/cnxDB'); app.post('/user ...

How can I optimize my .find query for a MongoDB GET request to achieve maximum performance?

I'm struggling to figure out how to retrieve only the last item stored in my database using a GET request. While I can successfully get the desired output in the mongo shell (as shown below), I haven't been able to replicate it in my GET route qu ...

Listening for value changes on a reactive form seems to be a challenge for me

While attempting to listen for value changes on a reactive form, I ran into the following error: This expression is not callable. Type 'Observable<string | null>' has no call signatures. searchWord = this.fb.group({ word: ['' ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

Connecting a string array to the navigation bar

Need Assistance with AngularJS: In my controller, I have a string array that looks like this: var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About&apos ...

Combining and linking 3 RxJS Observables in TypeScript and Angular 4 without nesting to achieve dependencies in the result

I have 3 observables that need to be chained together, with the result from the first one used in the other 2. They must run sequentially and each one should wait for the previous one to complete before starting. Is there a way to chain them without nestin ...

Excessive CPU usage caused by a patch in jQuery dealing with regular expressions

Working on a project developed by an unknown individual has presented some challenges. Without any means of contact with this person, I noticed that the browser's CPU consumption spikes significantly upon loading the page. Upon further investigation, ...

Using Express, Node, and Angular to transmit audio files to the frontend

I am currently working on serving audio files from a Node/Express backend to an Angular frontend. On the server side, the code looks like this: var file = "/filepath.wav"; res.download(file, 'testAudio.wav'); And here's the client side c ...

CKEditor seems to have overlooked the importance of proper paragraph formatting

Incorporating CKEditor into my front-end project using Laravel has been a great help. However, I am facing an issue where I want to eliminate automatic paragraphs but still allow users to create them by clicking the paragraph button. Is there a way to ac ...

Is there a way to change the text color of a table when hovering over an image using Javascript?

UPDATE: I believe I have solved the issue! However, if anyone has suggestions on a better way to achieve this, I am open to learning. I'm still fairly new to Javascript! I have an image and a table containing text. My goal is to change the color of S ...

Can WireMock be used to send an HTML file as a response?

Is it possible to return an HTML file as a response in WireMock and how can this be achieved? ...

Integration of Okta's oauth2 with an external Identity Provider (IdP

Currently, I have an Angular application with an Express server that utilizes Okta as an Identity Provider (IdP). The setup is functioning smoothly. However, the need has arisen to enable Single Sign-On (SSO) from an external application that utilizes Amaz ...

Utilizing a self-invoking function to incorporate JavaScript

In my role, I am responsible for managing a Content Management System (CMS) used by developers to create content that involves JavaScript. In the past, we placed the content in an iFrame for containment purposes; now, it operates as a single-page client-si ...

Discovering Virtual Directories within IIS using port 4200 in Angular

Having configured an IIS virtual directory with various photos, I am facing difficulty accessing it from my Angular App. A 404 NOT FOUND error is displayed when trying to access the directory. On the other hand, I can successfully access the folder using a ...