Modifying the property of an object following retrieval from the server

I find myself a bit perplexed about the optimal approach for modifying a value in an object once it has been retrieved from a server.

Here is my TypeScript Script:

import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { HttpService } from "../http.service";


@Component({
  selector: 'app-list-animals',
  templateUrl: './list-animals.component.html',
  styleUrls: ['./list-animals.component.css'],
  providers: [HttpService]
})
export class ListAgentsComponent implements OnInit {

    constructor(private httpService: HttpService) { }

    items: any[];

  ngOnInit() {
      this.httpService.getData()
          .subscribe(
          data => { this.items = data.resource; },
          error => alert(error),
          () => console.log("Finished")
          );
  }

}

This is how my template looks like:

<table class="standardTable">
    <tr *ngFor="let item of items"><td>{{item.type}}</td><td>{{item.summary}}</td><td>{{item.cost}}</td><td>{{item.available}}</td><td><a [routerLink]="['/animals/edit', item.id]">Now edit an animal</a></td></tr>
</table>

If the item.type equals "cat", I am deliberating on how and where to change it to say "feline". Should I make the alteration in the service, the TypeScript file itself, or implement a pipe?

Answer №1

To update the type of items in your service, you can utilize the forEach method:

ngOnInit() {
    this.dataService.fetchData()
      .subscribe(
      data => {
        this.items = data.results;
        this.items.forEach(item => {
          if(item.type === 'cat') {
            item.type = 'feline';
          }
        });
      },
      error => alert(error),
      () => console.log("Processing complete")
    );
  }

Answer №2

To update the array within your service, you can utilize Array.map():

ngOnInit() {
  this.apiService.fetchData()
      .subscribe(
      response => { 
          this.items = response.data.map(item => {
              if(item.type === 'dog') item.type = 'canine'
              return item;
          }); 
      },
      error => alert(error),
      () => console.log("Process completed")
      );
}

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

Dealing with undefined arrays in Angular across multiple templates: Best practices

I'm currently developing a search screen for an application and I've come up with three possible outcomes for the results section. If the user hasn't searched yet, then show nothing. If the user searches and the array is empty, display "no ...

What is the best way to create an interface tailored to a specific scenario using TypeScript?

In my TypeScript project without React, I am dealing with an interface structured like this: export interface LayerStyling<T> { attribute: string; value: AllowedTypes; type: LayerTypes; layout?: { icon: string }; state ...

Error: The JSON.parse method encountered an unexpected token 'h' at the beginning of the JSON string while trying to parse it

Here is the code snippet I wrote using Ionic framework: dialogflow(question) { let headers = new Headers(); headers.append('Content-Type','application/json'); return this.http.post('http://localhost:3000/api/dialogflow ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

What could be causing routerLink to malfunction despite correct configuration?

Is routerLink properly placed in the view? <p><a routerLink="/registration" class="nav-link">Register</a></p> Checking my app.module import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular ...

React Vite is encountering an error when processing CSS module files with the message 'Unable to locate module or its corresponding type declarations.'

After importing NavbarSample.module.css file, the content inside includes CSS styling for a .navbar class with specific properties like width, height, padding, display, flex direction, and border. However, when attempting to import this CSS module file in ...

It is not possible to use an async function with Ionic 4 ToastController buttons

Incorporating a new function into the handler of my ToastController button to return a promise (in this case: this.navCtrl.navigateForward()) is something I need assistance with. This is what my code looks like: const toast = await this.toastController.c ...

Unable to find solution for 'rxjs-compat/observable/combineLatest'

Recently, I updated my angular project to utilize "rxjs": "^6.3.3" Incorporating the combineLatest operator has caused complications after the upgrade, leading to compilation errors ERROR in ./node_modules/rxjs/observable/combineLatest.js Module not fo ...

`How can I incorporate typography into my Angular Material design?`

For my angular app, I am developing a custom theme and incorporating bootstrap's reboot to establish a basic starting point for non-material elements. To avoid conflicts with material variables, I converted the reboot into a mixin. In this mixin, I pa ...

Despite enabling CORS for a specific origin, I am still encountering the error message "No 'Access-Control-Allow-Origin'"

In my front-end application, I am using Angular to request API responses from a web API core project. Despite setting up cross-origin resource sharing for both running on different origins, I am still encountering an error stating 'No Access-Control-A ...

Utilize Angular2 to automatically fill dynamic forms with default data retrieved from an API

After spending a few weeks working with Angular 2, I am currently tackling the task of creating dynamic forms for a system settings page. The objective is to have the API return multiple forms, construct these forms within tabs, incorporate various types o ...

Troubleshooting React Typescript and Bootstrap - Issues with Collapse Component

I've encountered an issue in my React TypeScript app with Bootstrap 5. The app was set up using create-react-app and Bootstrap was added with npm i bootstrap. There is a button in the app that triggers the visibility of some content, following the ex ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

Using Typescript to replicate Object.defineProperties

Is there a way to emulate Object.defineProperties from JavaScript in Typescript? I am interested in achieving something similar using the syntax of Typescript: Object.defineProperties(someObject.prototype, { property: {get: function() { return v ...

Errors in typing occurring due to preact children within framer-motion

While working on my preact widget (https://github.com/preactjs-templates/widget), I noticed a connection to ReactDOM. import { motion } from 'framer-motion'; import { h, VNode } from 'preact'; const Test = () => { return <mot ...

Dealing with a sequence of deletions in Angular 4

When working with a ReplaySubject of size 3 and a delete chain that must be in order, I encountered an issue. After the deletion process is completed, I need to redirect the user. However, when subscribing to this ReplaySubject method, it sends "here fin ...

Using TypeScript: Inclusion of all object keys that correspond to a particular type

When working with an object type (or class type), I am looking to create a function that will take the object and a list of its keys as parameters. However, I specifically want to restrict the keys to only those that are mapped to a value of a certain type ...

Hidden back navigation strategy in AngularJS 2 with location strategy

After creating a custom LocationStrategy to disable browser location bar changes, I am now looking to integrate smaller apps into various web pages without affecting the browser's location. While navigation works smoothly with this new strategy, I am ...

Acknowledgment Pop-up

When using the PrimeNG table with a custom modal component that I created, I encountered an issue. The edit functionality works correctly and retrieves the correct row id, however, the delete function always returns the id of the first row. dashboard.html ...

Implementing Batch File Uploads using Typescript

Is there a way to upload multiple files in TypeScript without using React or Angular, but by utilizing an interface and getter and setter in a class? So far I have this for single file upload: <input name="myfile" type="file" multi ...