Changing the value within a nested object dynamically in Angular 6 during execution

Currently working with angular 6 and have a method like this:

 public Save(): void {
  this.data.station.parkingSlot.forEach(p => {
      if(p.isAvailable){
        p.isAvailable = false;
        this._carService.addCar(this.data);
        return true;
      }else{
         alert("all parking lots are taken")
      }
    })
  }

Looking to send the updated data (this.data) with isAvailable set to false as a parameter inside this._carService.addCar(this.data).

Below you can see how the this.data object looks. Notice that the last property isAvailable from parkingSlot is not updated to false as expected.

{
  "id": 3,
  "carType": "Spinter",
  "plateNumber": "BUS-XXX-XXX",
  "station": {
    "id": 2,
    "name": "STATION_2",
    "longitude": 3,
    "latitude": 4,
    "city": "Oslo",
    "streetName": "street1",
    "houseNumber": 55,
    "zipCode": 31000,
    "parkingSlot": [
      {
        "id": 1,
        "name": "PARKING_1",
        "isAvailable": false
      },
      {
        "id": 2,
        "name": "PARKING_2",
        "isAvailable": false
      },
      {
        "id": 3,
        "name": "PARKING_3",
        **"isAvailable": true**
      }
    ]
  }
}

Desired output:

{
  "id": 3,
  "carType": "Spinter",
  "plateNumber": "BUS-XXX-XXX",
  "station": {
    "id": 2,
    "name": "STATION_2",
    "longitude": 3,
    "latitude": 4,
    "city": "Oslo",
    "streetName": "street1",
    "houseNumber": 55,
    "zipCode": 31000,
    "parkingSlot": [
      {
        "id": 1,
        "name": "PARKING_1",
        "isAvailable": false
      },
      {
        "id": 2,
        "name": "PARKING_2",
        "isAvailable": false
      },
      {
        "id": 3,
        "name": "PARKING_3",
        **"isAvailable": false**
      }
    ]
  }
}

Seeking a solution to achieve this. Tried various approaches found through Google searches without success. Appreciate any help!

Additionally, I

Answer №1

Give this a shot! The issue lies in the premature addition to this.data. Make sure to update the array only after all the necessary information has been modified :)

public Save(): void {
    this.data.station.parkingSlot.forEach(p => {
        if(p.isAvailable){
            p.isAvailable = false;
            return true;
        } else {
            alert("all parking lots are taken")
        }
    });
    this._carService.addCar(this.data); // stores complete data in the this.data
}

Answer №2

The problem arises when the function addCar is called in every iteration, but ideally, it should only be executed once all flags are set to false.


public Save(): void {
  this.data.station.parkingSlot.forEach(p => {
      if(p.isAvailable){
        p.isAvailable = false;
        return true;
      }else{
         alert("all parking lots are taken")
      }
    })
    this._carService.addCar(this.data); // should be triggered after all 'isAvailable' flags are set to false.
  }

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

What is the best way to invoke a function and dynamically load a section of a view using AJAX?

I want to implement a feature where I can hide one div and load another div using an Ajax function. However, I am facing issues with redirecting to the function as intended. My goal is to load the div without having to refresh the page. <script type="t ...

Visibility issue in Three.js: Object not appearing immediately despite setting object.visible to true

I'm toggling visibility in my Three.js scene by using the .visible property on objects. Initially, certain objects (rooms) have their .visible property set to false. Once the camera enters a specific mesh (the room bounding box), the .visible propert ...

Ways to terminate and fulfill a promise

Each time I execute this snippet of code, a promise is returned instead of the data being inserted into my database. Unfortunately, I am unable to utilize the await keyword due to it not being in a top-level function. Specifically, I receive the message: & ...

Enhancing responsiveness in the auto-suggest feature

I am struggling to update the added value in the DOM after pushing a new element into the array of options. Despite my efforts, the update is not reflecting in the DOM. import { Component, OnInit } from '@angular/core'; import { FormControl } fro ...

Utilizing Jquery.validate() for personalized checkbox validation

My struggle lies in integrating jQuery.validate() with custom-designed checkboxes. I am unable to achieve the desired outcome where, upon clicking SUBMIT without selecting any checkboxes, an error should be displayed in the respective label. Despite having ...

Switch Angular checkbox to display string values instead of boolean true/false

My task is to create three checkboxes in a form with values toggling between "optin" and "optout" as I check/uncheck the checkboxes. Additionally, all checkboxes should be checked by default for the "optin" value. I'm struggling to find a solution, an ...

The component fails to load on the designated router outlet

I have updated my question to provide more clarity. I am working with 2 routing files, admin-layout.routing.ts and parameter.routing.ts. In admin-layout.routing.ts, there is a path for property.component.ts with a child called parameter.component.ts. Insid ...

Enhance your cloud functions by updating data

Recently, I encountered an issue with a function I wrote that interacts with the Real Time Database. Every time I attempted to write data to a specific node, it would add the complete dataset and then promptly delete everything except one entry. https://i ...

The object persists in revealing the password that I am attempting to conceal

Seeking help to hide the password object from being displayed. Below is my code snippet where I am using bcrypt to hash the password. Even though I am trying to hide the return object, I am not seeing the desired outcome. Can someone please point out wha ...

Retrieve the Array Object's Name in a JSON File

I am looking for city names like Salem and Madurai from the given JSON data { "status": "success", "DisplayList": [ { "AVINASHI": [ "gmail@com", "<a href="/cdn-cgi/l/email-protection" class= ...

Is there a way to deactivate a JavaScript function on a specific webpage using CSS?

I've implemented a JavaScript function that triggers a pop-up alert whenever a user attempts to navigate away from the site by clicking on an external link: $("a[target='_blank']").click( function() { return confirm('Please don&apo ...

Maximizing HTML5 Game Performance through requestAnimationFrame Refresh Rate

I am currently working on a HTML5 Canvas and JavaScript game. Initially, the frames per second (fps) are decent, but as the game progresses, the fps starts decreasing. It usually starts at around 45 fps and drops to only 5 fps. Here is my current game loo ...

Ways to showcase information based on the chosen option?

Is there a way to display data based on the selected value in a more efficient manner? Currently, when clicking on a value from the list on the left side, new data is added next to the existing data. However, I would like the new data to replace the existi ...

Reset the value of the input type file when the modal is closed and ensure that the Save All Changes button is deactivated

Hey there! Working on a simple project and trying to incorporate a neat trick in my app. I want to achieve the following: Clear the input type file value when the modal is closed. Essentially, if the user decides to cancel the upload and closes the modal, ...

Utilizing Cordova and jQuery-mobile to launch links in a separate device browser

My app has numerous links, all of which I have added rel='external' target='_blank' to. While this works perfectly in the Ripple emulator and regular desktop browsers, it doesn't function correctly on my Android device running JB 4 ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...

Caution: The Prop `href` did not meet the required criteria during the implementation of react server-side rendering

I'm currently utilizing react-router-dom and suspect that it may be the root of the issue at hand. However, I'm at a loss as to where to begin investigating or how to rectify it. Additionally, I'm encountering errors such as Warning: Did not ...

This code is only functional on JSFiddle platform

I encountered an issue with my code recently. It seems to only work properly when tested on jsfiddle, and I can't figure out why it's not functioning correctly on codepen or when run from local files. Why is this code specific to jsfiddle? When ...

Steps for launching a fresh script within the current tab

I'm currently working on a project where I have the following code: window.open("http://localhost/xyz.php") When this code runs, it opens the PHP file in a new tab within the same window. However, I'm trying to figure out how to make it open in ...

Exploring the functionalities of AngularJS' ng-options when working with select elements

In my search through other posts, I came across this issue but couldn't find a solution. Here is the array in question: $scope.items = [ {ID: '000001', Title: 'Chicago'}, {ID: '000002', Title: 'New York' ...