Create and save data to a local file using Angular service

I am facing an issue with my Angular service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { person } from '../interfaces/iperson';
import { item } from '../interfaces/iitem';

@Injectable({
  providedIn: 'root'
})
export class PeopleserviceService {

  constructor(private http: HttpClient) { }

  getPersonData(): Observable<person[]> {
    return this.http.get<person[]>('/assets/data/people.json');
  }
  completeTransaction(p: person, i: item){
    return this.http.get<person[]>('/assets/data/people.json').toPromise().then(peopleData => {
      if (!peopleData) {
        return Promise.reject(new Error('No data received'));
      }

      for (const pers of peopleData) {
        if (pers.id === p.id) {
          pers.balance -= i.price;
          break;
        }
      }

      return this.http.put('/assets/data/people.json', JSON.stringify(peopleData)).toPromise();
    });
  }
}

This setup is resulting in the following error:

ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found","url":"http://127.0.0.1:4200/assets/data/people.json","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://127.0.0.1:4200/assets/data/people.json: 404 Not Found","error":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot PUT /assets/data/people.json</pre>\n</body>\n</html>\n"}
    Angular 17
core.mjs:9171:22
    Angular 2
    RxJS 6
    Angular 14

Is there a way to make this angular page write locally to a file?

I have explored options like using the localforage package, but it doesn't seem to be working as expected.

Answer №1

assets/data/people.json resides on the server. When accessing from Localhost, both the client and server are located on the same machine. However, typically the server is situated remotely. Simply writing to a file on a server is not possible; you must establish a backend system (such as NodeJS with Express) and set up an endpoint that can receive data. Then, on the server side, you can write data to your file.

It's important to remember that this file is shared among all users; it's not for personal use only.

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

Angular can display text on hover based on the state shown in a <td> element

Working on an Angular 7 project, I have a <td> element where I display different colors to indicate the status of a task: Red - Indicates 'Delayed' Orange - Indicates 'In progress' Grey - Indicates 'Rejected' Cu ...

Troublesome Deployment of Angular on IIS 7.5: Why It's Not Going

My Angular project deployment is experiencing issues with a missing component. Workflow Step 1: I ran the following command: ng-build --prod Step 2: I added the website to IIS using the path inside dist. Step 3: The index page functions correctly, ...

What could be the reason that my Bootstrap dropdown menu is not appearing on my website

I am currently utilizing Angular in my project. I have incorporated bootstrap and jQuery via NPM install, and specified them as dependencies in angular.json. The navbar on my site contains a dropdown menu. When I hover over the dropdown menu, it should di ...

Type inference in TypeScript with transitivity

Consider this code snippet for illustration: function foo(t: "number"): number function foo(t: "string"): string function foo(t: "boolean"): boolean function foo(t: "number" | "string ...

Using Jest and Supertest for mocking in a Typescript environment

I've been working on a mock test case using Jest in TypeScript, attempting to mock API calls with supertest. However, I'm having trouble retrieving a mocked response when using Axios in the login function. Despite trying to mock the Axios call, I ...

The dynamically created array length is indicating as null

Although this question has been asked numerous times, most answers are in plain JavaScript. I have a function that generates an array with product data. This array is then utilized in another function to retrieve new data via JSON. $(function(){ var p ...

Troubleshooting compatibility issues between Sailsjs Services and TypeScript in Vscode

Having an issue with TypeScript in a Sails.js application. I am utilizing TypeScript to write my controller and attempting to use Sails.js services within the controllers. However, I encounter a syntax error in VSCODE. Below is the code snippet from MyCo ...

Typescript Nested Class (also known as Angular Private Inner Interface)

Utilizing a Nested Interface in an Angular Directive When working in Java, I have found static nested classes to be a helpful way to structure my code. Now, when trying to do something similar in Typescript with Angular, I'm running into some challen ...

Tips for Preserving Empty Elements When Parsing JSON in R

Currently, I am facing a challenge with parsing JSON data that is structured as an array of arrays. This structure resembles a table of data, where the elements within the arrays can be either empty or contain nested arrays and objects. Below is an example ...

Submit information by utilizing' content-type': 'application/x-www-form-urlencoded' and 'key': 'key'

Attempting to send data to the server with a content-type of 'application/xwww-form-urlencode' is resulting in a failure due to the content type being changed to application/json. var headers= { 'content-type': 'applica ...

ways to pinpoint a precise object pathway within a JSON

Working with json4s to parse a JSON into a Scala case class object has been successful so far: case class Person(Id: String, name: String) val personJSON = """[ {"Id": "1","name": "john"}, {"Id": "2","name": "george"}, ...

Tips for Managing the Hardware Back Button in Ionic 3

Can someone help me enable the hardware back button in Ionic 3? I want it to redirect to specific pages and display designated content. Being new to Ionic 3, I need guidance on how to set up the hardware device buttons for redirection. ...

Filtering JSON API response based on the name parameter

I've searched through numerous similar questions and discussions, but none have provided a solution to my problem. I am working with an API response that contains a list of jobs executed on a virtual machine. Specifically, I am interested in summarizi ...

Mastering Angular Service Calls in TypeScript: A Comprehensive Guide

In the midst of my TypeScript angular project, I am aiming to revamp it by incorporating services. However, I have encountered an issue where when calling a function within the service, the runtime does not recognize it as the service class but rather the ...

Storing keys as strings instead of integers in a JSON dictionary

I recently stored a dictionary in JSON format for future use in various applications. The structure of the dictionary is as follows: dictionary = { 1: 'Name', 2: 'Name2', 3: 'Name3' } To save it, I used the foll ...

Looking to retrieve object values in JavaScript in a dynamic manner?

Imagine having an array of objects with nested objects. The data is always changing, meaning the keys may vary each time. For instance: [ { "uuid": "53e7202c-28c8-4083-b910-a92c946a7626", "extraIdentifiers": { "National ID": "NAT2804" }, ...

"Troubleshooting the issue of Angular's select binding causing a disruption

The Angular version being used is 1.4.7. Within the model in question, there are two objects: 'systems', which is an array, and 'selectedSystem'. The desired outcome is for 'selectedSystem' to reference one of the objects wit ...

Using Jasmine to simulate an if/else statement in Angular/Typescript unit testing

After making a minor change to an existing function, it has been flagged as new code during our quality checks. This means I need to create a unit test specifically for the new 4 lines of code. The challenge is that there was never a unit test in place for ...

Is it possible for me to convert a .map array into a comma-separated array enclosed in double quotation marks?

I am attempting to extract data from a group of twig variables and convert them into a javascript plugin. The data consists of dates listed in an array format. Initially, they are displayed on the template as a string like this: {"date":"2018-08-30, 2018- ...

Using Generic Types in Response DTO with Typescript, NestJs, and Class Transformer

In my project, I am dealing with multiple endpoints that provide responses along with pagination details. My goal is to have a single parent type for the pagination and be able to use different data types for the data parameter. I attempted the following ...