Angular 8 encountered a 404 (Not Found) error when trying to POST to http://localhost:4200/assets/data/students.json

I'm currently working on a project that involves fetching array data through HTTP and should also allow for the addition of new arrays using HTTP. However, every time I attempt to post a new array, I encounter the following error:

POST http://localhost:4200/assets/data/students.json 404 (Not Found)

This issue is puzzling because I can successfully fetch data from the URL without any errors, but adding a new array seems to be problematic.

Here's an overview of my project structure:

https://i.sstatic.net/UHiQH.png

student.service.ts:

import { Injectable } from '@angular/core';
import {HttpClient,HttpErrorResponse,HttpHeaders} from '@angular/common/http';
import { IStudent} from './student'
import { Observable, of } from 'rxjs'
 import { catchError,map, tap } from 'rxjs/operators'
@Injectable({
  providedIn: 'root'
})
export class StudentService {

private  _url:string = "/assets/data/students.json";

constructor(private _http : HttpClient) { }

   delete(id: number) {
     return this._http.delete(`/student/` + id);
 }

 getStudents():Observable<IStudent[]>{
   return this._http.get<IStudent[]>(this._url);
 }


  addStudent(student : IStudent ):Observable<IStudent>{
    return this._http.post<IStudent>(this._url,student);
  }




}

student.ts

export class IStudent{
  id:number;
  name:string;
  age:number
}

/assets/data/students.json

[
  {"id":1,"name":"John","age":22},
  {"id":2,"name":"Austine","age":26},
  {"id":3,"name":"Samantha","age":24},
  {"id":4,"name":"Lily","age":25}
]

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule,routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { StudentListComponent } from './student-list/student-list.component';
import { StudentDetailComponent } from './student-detail/student-detail.component';
import { FormsModule } from '@angular/forms'
import {StudentService} from './student.service';
import {HttpClientModule} from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    StudentListComponent,
    StudentDetailComponent,
    routingComponents
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
  ],
  providers: [StudentService],
  bootstrap: [AppComponent]
})
export class AppModule { }

student.detail.ts

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute,Router,ParamMap } from '@angular/router';
import {StudentService} from '../student.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {IStudent} from '../student';
import { HttpClient } from "@angular/common/http";
@Component({
  selector: 'app-student-detail',
  template: `
  <h2>Student Form</h2>
  <ul class="student" >
      <li   *ngFor = "let student of students">
      <span class="badge">{{student.id}} {{student.name}} {{student.age}}</span>
  </li>
</ul>
  <form >
  <div class="form-group">
      <label>ID:</label>
      <input #SID type="number"  class="form-control" id="id" name="id">
</div>

    <div class="form-group">
      <label>Name:</label>
      <input  #SName type="text"  class="form-control" id="name" name="name">
</div>
<div class="form-group">
      <label>Age:</label>
      <input #SAge type="number"  class="form-control" id="name" name="name">
</div>

<button (click)="add(SID.value,SName.value,SAge.value)" type="submit">Add</button>
</form >


 `,



  styleUrls: ['./student-detail.component.css']
})
export class StudentDetailComponent implements OnInit {

 public students = [];
public studentId;
public studentName;
public studentAge;
registerForm : FormGroup;


  constructor(private route : ActivatedRoute,private router: Router,private _studentService: StudentService) { }


  ngOnInit() {
    this._studentService.getStudents()
      .subscribe(data => this.students = data);
      }

        add(id:number,name:string,age:string): void {
         this._studentService.addStudent({ id } as IStudent)
           .subscribe(student => {
             this.students.push(student);

           });
       }
      }

Answer №1

Attempting to write to a local file is not supported by JavaScript.

To work around this limitation, consider using an array variable in your service and implementing methods to push data onto it for storage and retrieval.

Answer №2

According to durai's comment, I decided to create a service with an array and write methods for pushing data onto it as well as retrieving it.

In order to accomplish this, I created a new service along with a mock database to store the array. This allowed me to successfully populate the array with new data. For reference, I found this website to be very helpful: https://angular.io/tutorial/toh-pt6#simulate-a-data-server

Below is my new service designed to manage the array:

import { InMemoryDbService } from 'angular-in-memory-web-api';
import {IStudent} from './student';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class InMemoryDataService implements InMemoryDbService{

  createDb() {
    const students = [
  {"id":1,"name":"John","age":22},
  {"id":2,"name":"Austine","age":26},
  {"id":3,"name":"Samantha","age":24},
  {"id":4,"name":"Lily","age":25}
    ];
    return {students};
  }

  genId(students: IStudent[]): number {
    return students.length > 0 ? Math.max(...students.map(student => student.id)) + 1 : 11;
  }

  constructor() { }
}

And here is the service responsible for managing the retrieval and addition of data in the array:

import { Injectable } from '@angular/core';
import {HttpClient,HttpErrorResponse,HttpHeaders} from '@angular/common/http';
import { IStudent} from './student'
//import 'rxjs/add/operator/catch';
//import 'rxjs/add/Observable/throw';
import { Observable, of } from 'rxjs'
 import { catchError,map, tap } from 'rxjs/operators'

@Injectable({
  providedIn: 'root'
})
export class StudentService {
private  _url = 'api/students';

constructor(private _http : HttpClient) { }

//   getAll() {
//      return this._http.get<Student[]>(`/students`);
//  }


  delete(id: number) {
     return this._http.delete(`/student/` + id);
 }

 getStudents():Observable<IStudent[]>{
   return this._http.get<IStudent[]>(this._url);
 }

 getStudentsbyId(id: number): Observable<IStudent> {
  return this._http.get<IStudent>(this._url);
}

addStudent (student : IStudent): Observable<IStudent> {
  return this._http.post<IStudent>(this._url, student)
  ;
}

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

Encountering errors during 'npm i' - issues arising from unresolved dependency tree

Recently, I have been facing issues with running npm i as it keeps failing and showing an error. The project is using Angular 15 without any previous errors, so it's puzzling why there is suddenly a complaint about Angular 16. npm ERR! code ERESOLVE n ...

Is it possible that jest is unable to catch the exception?

I have a simple function that looks like this: function foo({ platform }) { if (platform === 'all') { throw new Error('Platform value can only be android or ios'); } return `${platform}`; } After writing unit tests, the re ...

What might be causing my action function to be triggered during the rendering process?

While working on creating a basic card view in material UI, I encountered an issue where the functions for adding and deleting items seem to be triggered multiple times upon rendering. I am aware that a common reason for this could be using action={myFunc ...

A guide on displaying an Angular Component within a Thymeleaf page

Currently, I am faced with the task of integrating Angular and Thymeleaf. This is necessary because I have developed a dynamic graph using Angular and now need to incorporate it into an existing project that utilizes Thymeleaf. Are there any simplified m ...

Utilizing dynamic data within the ng-template

As a newcomer to Angular, I am facing a challenge in passing a string into a template. My goal is to create a reusable template or component that can display instructions on how to proceed with an action. Currently, I am achieving this by using the follow ...

A generic type in TypeScript that allows for partial types to be specified

My goal is to create a type that combines explicit properties with a generic type, where the explicit properties have priority in case of matching keys. I've tried implementing this but encountered an error on a specific line - can anyone clarify why ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

The slides in Swiperjs are having trouble moving smoothly

I am experiencing some challenges with swiperjs where the slides are not snapping to the next slide and I am unable to fetch the active index from them. Below is a snippet of my code where I am using typescript, swiperjs version 6.84, and the Ionic frame ...

Combining TypeScript into HTML resulted in an error: Uncaught ReferenceError clickbutton is not defined

Attempting to create a basic CRUD frontend without the use of any frameworks. I am encountering an issue when trying to include a TypeScript file (index.ts) in my index.html, as the functions called within it are showing as undefined. I understand that bro ...

Directive for displaying multiple rows in an Angular table using material design

I am attempting to create a dynamic datatable with expandable rows using mat-table from the material angular 2 framework. Each row has the capability of containing subrows. The data for my rows is structured as an object that may also include other sub-ob ...

Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors? I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges. ...

Empowering user accessibility through intricate custom elements

In the world of web accessibility guidelines, labels are typically associated with form controls like <input> or <textarea>. But what happens when dealing with complex Angular / React / ... components that function as form controls? Picture a ...

Angular - Exploring the process of creating a secondary standalone build for a specific section of an application

I have created an Angular 4 (or 5) application with a specific structure as shown in the image below: https://i.sstatic.net/zK1BM.png Now, I need to develop a separate standalone angular application where only a selected group of Angular components from ...

Oops! There seems to be an issue: "ERROR TypeError: Unable to access the 'getMonth' property of

I have integrated a date-timepicker into my reactive form on Angular 6/7 without applying a form-control to it. I am using an angular2 datetimepicker - import { AngularDateTimePickerModule } from 'angular2-datetimepicker'. However, I'm enco ...

Typescript double-sided dictionary: a comprehensive guide

Looking for a dual-sided dictionary implementation in TypeScript that allows you to retrieve values using keys and vice versa. An initial approach could be storing both items as keys: dict = {"key": "value", "value": "key"} But I am curious if there are ...

Creating a variable as a list of string arrays in TypeScript

Currently working with Angular 2.0, I am trying to declare a variable in a Typescript file that is a list of string arrays. I attempted using yAxis_val: list, but it is not functioning correctly. If anyone knows the proper way to achieve this, please prov ...

Creating a Lambda function in CDK: A guide to configuring the Dockerfile and setting environment variables

I am currently working on a SAM project using template.yml. Here is a snippet of the configuration: Globals: Function: Timeout: 30 Environment: Variables: DBNAME: !Ref DBNAME Resources: MessageFunction: Type: AWS::Serverless: ...

Angular 5 custom dropdown menu

Currently, I am utilizing the ng-select component available at https://github.com/ng-select/ng-select. However, there are instances where the content of the dropdown is too lengthy. To address this issue, I have decided to shorten the string in the dropd ...

Exploring TypeScript and node.js development using Visual Studio 2012 express

Is there a way to successfully write, build, and execute a node.js application in Visual Studio? I have already installed the TypeScript extension on VS as well as the node.js package. However, when I attempt to create a new project of the TypeScript type, ...

Encountering issues with Semver while working on building an Angular 4 IMAP client

I am currently working on integrating an Imap Client into my Angular 4 app. I came across a helpful node module for implementing Imap using npm: Repository However, I encountered an issue. After adding the following line in angular-cli.json: "scripts": ...