Modify an individual attribute in a local JSON file using a put request in Angular 8

I am looking to make updates to my JSON file located in the assets folder. Specifically, if I want to update just one property of my JSON object, I would like it to only affect that particular property without impacting any others:

For example, in the sample code below:

loginInterface.ts

export interface loginModel {
    Email: string;
    Password: string;
}

login.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http'
import { loginModel } from './loginModel'

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {


  private _jsonURL = 'assets/Login.json';
  private login: Array<loginModel>;

constructor(
    private http: HttpClient) {
    this.login = new Array<loginModel>();
  }
ngOnInit() {
    this.getLoginData();
  }

  getLoginData() {
    this.http.get<loginModel[]>(this._jsonURL).subscribe(data => {
      this.login = data;
      console.log(this.login);
      return this.login;
    });
  }

UpdateLoginData() {
// How do I handle this??
  }
}

login.component.html

<div *ngFor = "let log of login">
    {{log.Email}} 
    <input [ngModel]="log.Password">
</div>
<button (click)="UpdateLoginData()">Update</button>

This is just an example.

If I change the password for one email and click on the update button, I want it to only update the password for that specific email without replacing the entire JSON file with a new object. Is there a way to achieve this?

Answer №1

File operations cannot be performed solely with the Angular framework. A server-side implementation is required to accomplish this task. If you are unfamiliar with server-side programming, you may consider using the in-memory Angular database API.

https://www.npmjs.com/package/angular-in-memory-web-api

Answer №2

Modifying the content of a JSON file through Angular directly is not possible; you must have a Backend to implement the changes to the JSON file.

Answer №3

Sorry, but Angular does not support directly changing a file's content. This type of operation is typically handled by a backend framework or language like Node.JS that has access to file system APIs. One way to work around this limitation is to create a RESTful API that allows for modifying file contents and make an HTTP request from your Angular application.

Answer №4

One way to update data in a json server is by using the put method, as shown below:

this.http.put(this._jsonURL+this.login[0].id,this.login[0]).subscribe();

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 could be causing the shake effect on the MUI dialog to not work when clicking away?

I am trying to implement a shake effect when the user clicks outside the MUI dialog to indicate that clicking away is not allowed. However, the code I have so far does not seem to be working as the effect is not being applied. Can someone please help me ...

Guide to automatically filling in a form's fields with information from a database by clicking on a link

Currently, I have a form in HTML that is designed to gather user/member information. This form connects to a database with multiple columns, with two key ones being "user_email" and "invoice_id". Upon the page loading, the input for "user_email" remains hi ...

Determine in an efficient way during mouseover if the control key is being pressed with Vue

My initial approach to tracking whether the control key (ctrl) is pressed while hovering over a <section> is as follows: <template> <section v-on:mouseover="controlKeyPressed = $event.ctrl">...</section> </template> Howeve ...

Creating numerous duplicates of a highly nested immutable Object can be done by using a combination of spread operators

I am currently working on retrieving data from firebase/firestore using Javascript. I have created a function where I retrieve my products collection and pass this data to the React state.products by utilizing the setState() method. My objective is to tra ...

"JavaScript issue: receiving 'undefined' when trying to retrieve input

This code snippet is for a web app that tracks the number of losses in a game. The problem arises when trying to retrieve the value, which returns undefined. Every time I reference the username variable, it returns undefined. document.addEventListener(&a ...

The Node.js error message reads: "Cannot set headers after they have been sent" while trying to make a post request

Yes, I understand this issue has been addressed multiple times on stackoverflow, but unfortunately, I haven't found a solution that works for me. The problem arises when trying to make a post request on my nodejs server. The error message states &apo ...

Incorporating a classList.toggle into a snippet of code

button, p, h1, h2, h3, h4, h5, a{ /* Define specific elements to use "fantasy" font */ font-family: Tahoma; } #main_body{ margin: 0px auto; background-color: #dedede; } #top_body{ /* Remove margin for simplicity */ } #t ...

Avoid repeating the base URL when creating services using the intercept service concept

Greetings, I must begin with an apology for any confusion in my explanation of the issue at hand. Currently, as part of a project I am working on, the Base URL or Environment URL is defined within the InterceptService. However, there seems to be an anomal ...

Visitors may not immediately notice the CSS/JavaScript modifications in their browsers

Currently, I am working on a web application utilizing Spring MVC and Hibernate, deploying it on Apache Tomcat 8. Most of my users access the app using Google Chrome. However, I have encountered an issue where whenever I update the CSS or JavaScript files ...

I'm struggling with an issue of being undefined in my React.js project

This code snippet is from my app.js file import React, { useState, useEffect } from "react"; import { v4 as uuid } from "uuid"; import "./App.css"; import Header from "./Header"; import AddContact from "./AddCo ...

Inspect the data attribute and modify the class

I am looking to determine if a data attribute has a specific value and then update the class associated with it. For example, in my HTML code: <li class="country active" data-country-code="ca"><div class="flag ca"& ...

Methods of obtaining the array size using interpolation in Angular2?

Is there a way to inquire about the size of an array in Angular 2 when it is used within a component? For instance, consider the following: users : User[]; where export class User { id : number; firstName : String; lastName : String; userName ...

After the page is reloaded, apply a class to the divs by selecting them based on the "data" attribute

I have a set of four cards labeled "card", each representing different body parts: eyes, torso, arms, and legs. <div class="card" data-lesson="eyes">eyes</div> <div class="card" data-lesson="torso">torso</div> <div class="card" ...

What could be causing the issue with my hour parameter in node-cron?

Having difficulty setting up a cron job to run with node-cron every Monday at 8:30. I've tried using "30 8 * * Mon" and even "30 08 * * Mon", but it doesn't seem to work. Interestingly, "30 * * * Mon" does work and runs every hour on the 30th min ...

Assign a class to each offspring of a slot

I am currently in the process of setting up a component with a slot that, upon rendering, adds a specific class to each child within that slot. To simplify: <template> <div> <slot name="footerItems"></slot> </div> ...

Having trouble with Angular minification not properly updating templates?

As a newcomer to angular development, I am currently working on creating components for AEM 6.2 using angular and utilizing gulp to minify the js files for all the components. In my gulpfile, I have set up the following configuration: var uglify = require ...

Cross domain requests with jQuery's getJSON function

Struggling to fetch data using jQuery Cross Domain from GitHub, but hitting a roadblock! I've come across suggestions to use jsonp requests, but can't seem to figure out what's going wrong. http://jsfiddle.net/jzjVh/ Chrome seems to be int ...

When the button is clicked, verify the existence of the file, then display a message and undo

I encountered a situation where I needed to verify if a user tries to input data with the same date and same region again, they should receive a prompt alert. I attempted to achieve this using code in the backend, as shown below:- protected void btnSave ...

Having trouble changing the Font Awesome icon on click?

I'm struggling to figure out why I can't change a font awesome icon using a toggle. I've tried various solutions but nothing seems to be working. Any insights on what might be causing this issue? (HTML) <span class="toggle-icon" ...

Validating Credit Card Expiration Dates in AngularJS Form

I recently started learning AngularJS and decided to create a credit card validator. I successfully implemented the Luhn Algorithm in a custom filter, but now I'm facing issues with validating the expiration date as well. The conditions for a valid ex ...