У меня есть простой проект JSON CRUD в Angular 9. Я использую json -сервер для доступа к данным из локального файла JSON (products. json). Я могу получить данные из этого json файла без каких-либо ошибок, но если я попытаюсь добавить новый элемент в продукты. json файл, используя сообщение, я всегда получаю ошибку ниже:
HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: "Internal Server Error", url: "http://localhost:3000/products", ok: false, …}error: "TypeError: Cannot read property 'id' of undefined↵ at Function.createId at Function.insert...
Пожалуйста, помогите.
Пожалуйста, проверьте ниже код, который я пробовал:
продукты. json
{
"products": [{
"name": "Moto G5",
"qty": "20"
},
{
"name": "Rdmi Note5 Pro",
"qty": "50"
},
{
"name": "Nokia 3310",
"qty": "40"
}
]
}
============ ================================================== ===
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ProductsComponent } from './products/products.component';
import { FormsModule} from '@angular/forms';
import { ProductService } from './product.service';
import { HttpClientModule } from '@angular/common/http';
import { AboutComponent } from './about/about.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { ProductComponent } from './product/product.component';
@NgModule({
declarations: [
AppComponent,
ProductsComponent,
AboutComponent,
PageNotFoundComponent,
ProductComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [ProductService],
bootstrap: [AppComponent]
})
export class AppModule { }
============================= =========================================
продукты. Компонент .ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ProductService } from '../product.service';
import { Product } from './product';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
constructor(private _prodService:ProductService, private _route:ActivatedRoute){}
productList:Product[];
title:string="Products List"
ngOnInit(){
this.getProducts();
}
@Input() companyName:string;
@Output() addedProduct=new EventEmitter();
productName:string;
quantity:number;
prodName:string;
prodQty:number;
getProducts()
{
this._prodService.GetProducts().subscribe((data:Product[]) => {
this.productList = data;
});
}
AddProduct() {
let newProd:Product={
name:this.prodName,
qty:this.prodQty
}
this._prodService.AddProduct(newProd).subscribe((data:any)=>{
console.log(data);
});
}
}
======================================= ======================================
product.service.ts
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Product } from './products/product';
const headerOption={
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
@Injectable()
export class ProductService {
constructor(public http:HttpClient) { }
url = 'http://localhost:3000/products';
GetProducts():Observable<Product[]>{
return this.http.get<Product[]>(this.url,headerOption);
}
AddProduct(newProd:Product):Observable<Product>{
return this.http.post<Product>(this.url,newProd,headerOption);
}
}
========================================== ===============================================