Manipulate product data within a JSON file using Angular 2, utilizing HTTP requests and observables

Is there a way to manage products/items in a JSON file using Angular2 with HTTP and observables? I have successfully implemented GET Products, but need guidance on how to Add/Update/Delete items. Below is the code for reference:

product-list.component

export class ProductListComponent implements OnInit {
pageTitle: string = 'Product List';
imageWidth: number = 50;
imageMargin: number = 2;
showImage: boolean = false;
listFilter: string;
errorMessage: string;

products: IProduct[];

constructor(private _productService: ProductService) {

}

toggleImage(): void {
    this.showImage = !this.showImage;
}

deleteItem() : void {
    this._productService.deleteProduct();
}
ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                       error => this.errorMessage = <any>error);
}

product.service.ts

export class ProductService {
private _productUrl = 'api/products/products.json';
private headers = new Headers({'Content-Type': 'application/json'});

constructor(private _http: Http) { }

getProducts(): Observable<IProduct[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IProduct[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

deleteProduct(): Observable<IProduct[]> {
    let id : number = 1;        
    return this._http.delete(`${this._productUrl}/${id}`) 
                     .map((res:Response) => res.json()) 
                     .catch((error:any) => Observable.throw(error.json().error || 'Server error')); 
}   

product-list.component.html

<tbody>
                <tr *ngFor='let product of products | productFilter:listFilter'>
                    <td>
                        <img *ngIf='showImage'
                             [src]='product.imageUrl'
                             [title]='product.productName | uppercase'
                             [style.width.px]='imageWidth' 
                             [style.margin.px]='imageMargin'>
                    </td>
                    <td><a [routerLink]="['/product', product.productId]">
                        {{product.productName}}
                        </a>
                    </td>
                    <td>{{ product.productCode | lowercase }}</td>
                    <td>{{ product.releaseDate }}</td>
                    <td>{{ product.price | currency:'USD':true:'1.2-2' }}</td>
                    <td>
                        <ai-star [rating]='product.starRating'
                                (ratingClicked)='onRatingClicked($event)'>
                        </ai-star>
                   </td>
                   <td>
                       <button class="delete"(click)="delete(product); $event.stopPropagation()">X</button>
                   </td>
                </tr>
            </tbody>

JSON file

[
{
    "productId": 1,
    "productName": "Leaf Rake",
    "productCode": "GDN-0011",
    "releaseDate": "March 19, 2017",
    "description": "Leaf rake with 48-inch wooden handle.",
    "price": 19.95,
    "starRating": 3.2,
    "imageUrl": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png"
},
{
    "productId": 2,
    "productName": "Garden Cart",
    "productCode": "GDN-0023",
    "releaseDate": "March 18, 2017",
    "description": "15 gallon capacity rolling garden cart",
    "price": 32.99,
    "starRating": 4.2,
    "imageUrl": "http://openclipart.org/image/300px/svg_to_png/58471/garden_cart.png"
},
{
    "productId": 5,
    "productName": "Hammer",
    "productCode": "TBX-0048",
    "releaseDate": "May 21, 2017",
    "description": "Curved claw steel hammer",
    "price": 8.9,
    "starRating": 4.8,
    "imageUrl": "http://openclipart.org/image/300px/svg_to_png/73/rejon_Hammer.png"
},
{
    "productId": 8,
    "productName": "Saw",
    "productCode": "TBX-0022",
    "releaseDate": "May 15, 2017",
    "description": "15-inch steel blade hand saw",
    "price": 11.55,
    "starRating": 3.7,
    "imageUrl": "http://openclipart.org/image/300px/svg_to_png/27070/egore911_saw.png"
},
{
    "productId": 10,
    "productName": "Video Game Controller",
    "productCode": "GMG-0042",
    "releaseDate": "October 15, 2017",
    "description": "Standard two-button video game controller",
    "price": 35.95,
    "starRating": 4.6,
    "imageUrl": "http://openclipart.org/image/300px/svg_to_png/120337/xbox-controller_01.png"
}

]

Answer №1

In response to your query on the discussion Tab for this particular course, I have provided an answer:

It is not possible to manipulate rows in the product.json file through http methods like add, update, or delete. Only the get method can be used.

If you want to perform operations such as adding, updating, and deleting data using http, a back-end server is necessary. However, there is an option of utilizing an in-memory back-end server for trying out these actions without the need to set up a complete back-end server.

To explore further details and view sample code, please visit:

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

Extracting a precise 14-digit numerical value from a JSON file using Java

Working with a JSON source obtained from an API at my workplace, I am tasked with extracting the balance from the JSON response. This value is crucial and usually appears in the format of xx.xxxxxxxxxxxxxx, which consists of two digits followed by up to 14 ...

What is the best way to access a nested element within a JSON string using Scala?

Currently, I am utilizing Scala to parse JSON with a specific structure: { "root": { "metadata": { "name": "Farmer John", "hasTractor": false }, "plants": { "corn": 137.1 ...

Guide on retrieving URL from backend to iframe with Angular Material selection change

https://i.sstatic.net/mWBb5.png This is an .html page <iframe width="100%" height="100%" src="{{url}}" frameborder="0" allowfullscreen></iframe> Here is the code for a .ts file this.url = 'https://www.youtube.com'; Whenever a sel ...

The AppModule has imported an unexpected value of '[object Object]', causing errors

How can I properly import the Pipe Module into my Angular app? import { NgModule } from '@angular/core'; import { PipeTransform, Pipe } from '@angular/core'; @Pipe({ name: 'values', pure: false }) export class CustomPipe im ...

Generate a DataContract Class in C# based on JSON with dynamically generated keys

Do you need help accessing dynamically generated attributes in your C# code? Let's say you have a sample JSON structure like this: {"'1234xxxxxx'":[{"AttributeId":"1","AttributeName":"Brand","AttributeValue":""},{"AttributeId":"2","Attribu ...

What is the best approach to implement server-side rendering in Next.js while utilizing Apollo React hooks for fetching data from the backend?

I have a Next.js project that is utilizing Apollo GraphQL to retrieve data from the backend. My goal is to render the page using server-side rendering. However, I am encountering an obstacle as the React hooks provided by GraphQL Apollo prevent me from cal ...

Exploring the world of JSON and JavaScript data structures

Can someone provide some clarification please? var a = '{"item":"earth", "color":"blue", "weight":920}'; Is the data type of a a string or an array ? var b = JSON.parse(a); What is the data type of b - an object or an array ? ...

Retrieve the specific key or object number by conducting a search in JavaScript

I am faced with the challenge of editing a large XML file by searching for a specific keyword within the "event name" field and changing the corresponding "active" value to either 1 or 0. The structure of the data file is as follows. I have managed to modi ...

Loading JSON data into a dropdown menu

Despite my efforts to search and experiment with different methods, I have been unable to find a suitable solution for my current situation. After making an AJAX query, I received the following JSON format: [{"id":1,"region":"Region I","state_id":1},{"id ...

Retrieve the HTML tag content as a string using jQuery

For my OSINT project, I am developing a tool that needs to extract text from a specific HTML code string. $("p").text(); I'm looking for a way to make my variable work with the above code. Any suggestions? Share your ideas! Solution: $.ajax({ ...

Looking for a way to efficiently add multiple value inputs to a JSON object using jQuery or JavaScript?

Here is the HTML input tag code I am working with: <form id="info"> <input id="A" name="A" type="hidden" nodetye="parent" value="A"> <input id="A1" name="A1" type="text" nodetype="child" value="a1val"> <input id="A2" name ...

Deleting button on Angular 4's CKEditor

Currently, I am utilizing version 4.7.3/basic/ckeditor.js and seeking guidance on how to eliminate the "About" and "NumberedList" buttons. Does anyone have a solution for this? <ckeditor [(ngModel)]="work.points" [config]="{removePlugins: 'Ab ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

PHP fails to return any data when JSON data is not decoded

After fetching json data from a blob field in my MySQL database and using the Laravel framework, everything seems to be functioning correctly. However, I am encountering an issue where the JSON data retrieved from the blob field is not being decoded prop ...

Tips for troubleshooting a Keycloak-enabled Angular/Java/Spring application:

Recently, I developed a basic application that leverages keycloak for managing user authentication. However, I am interested in making certain routes accessible to the public. For example, something along the lines of localhost:4200/public-route. I attemp ...

Guide on performing arithmetic subtraction of identical key values in 2 JSON files and displaying the result in an output JSON file

I have two json files with the same key fields in each file. I need help performing arithmetic subtraction on the values of corresponding key fields between the two files and then outputting the result into a third json file [delta of two json files to out ...

Is it possible to conditionally remove the parent upon the loading of the Router?

Below is the content from my component.html file: <content-placeholder></content-placeholder> <router-outlet></router-outlet> I would like to know if there is a way to hide or remove the <content-placeholder></content-pla ...

Try skipping ahead to the following spec file even if the initial spec has not been completed yet

I have encountered an issue when trying to execute two spec files for Angular.js. The problem arises when I attempt to run both files consecutively - the browser initially opens for angular.js, then switches to angularCal.js without executing angular.js ...

responseJSON for the fine uploader

I am experiencing an issue with the code below. Despite expecting a JSON object, I am only receiving a string containing the file name. var app=$('#failed-fine-uploader').fineUploader({ request: { endpoint: 'media/upload.php&apo ...

What is the best way to change the routerLink destination when it is active?

With the angular2/4/5/6 router, I have multiple links: <a [routerLink]="/page1" [routerLinkActive]="class here">Link 1</a> <a [routerLink]="/page2" [routerLinkActive]="class here">Link 2</a> <a [routerLink]="/page3" [routerLinkA ...