Ways to disregard attributes passed through HTTP

In my application's interface, I manage certain properties that need to be sent to the database while excluding others.

One specific property I handle is called state, which can have a value of open or null (closed). This property triggers Angular2's Animation state function. I utilize this in lists using *ngFor to toggle the visibility of information panels related to each item.

However, since the default value for state is always null, I prefer not to store it in the database. Currently, when making an HTTP call, the entire object is passed along including the state property. Is there a way to ignore this specific property?

  pushItemToDay(item: any, dateStr: Date): void {
    let body = JSON.stringify(item);

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    this.http.post(this.baseURL + 'api/addItem/' + dateStr, body, options)
        .toPromise()
        .catch(this.handleError);
  }

Answer №1

Using the delete function can cause issues if the object is accessed post-deletion. To prevent unwanted entries from being included, the stringify function offers an additional parameter for exclusion.

let input = {
  'fruit': 'apple',
  'drink': 'orange juice',
  'snack': 'chips',
  'dessert': 'ice cream'
};
let excludeList = ['snack', 'dessert'];

function filterOut(key, value) {
    if (excludeList.indexOf(key) > -1) return undefined;
    else return value;
}

let result = JSON.stringify(input, filterOut);
console.log(result);

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

Having trouble connecting 'chartData' to a 'div' in Angular 2 because it is not recognized as a valid property?

While working on my Angular project, I encountered the following error that I have been unable to resolve: EXCEPTION: Uncaught (in promise): Error: Template parse errors: Can't bind to 'chartData' since it isn't a known property of ...

Switching Angular repository to download node_modules dependencies from internal company source: A step-by-step guide

Within my company, we have an internal artifactory where all the dependency libraries must be sourced from. It is not possible for me to download them from the internet using 'npm install'. Upon examining the package-lock.json file, I noticed th ...

Leveraging d3.js for Visualizations in an Angular2/Node/Express/MongoDB Application

I’m working on integrating d3.js (https://www.npmjs.com/package/d3) into my project, and upon loading the page, I encounter a ZoneAwareError. After executing npm install d3 --save, all dependencies were successfully installed. Although I followed the gui ...

Get the file without specifying type in request - Angular

Is it possible to download a file solely through the response without specifying a responsetype in the header? I am looking for a way to download the file without including any additional parameters in the header. ...

Having trouble retrieving user attributes from the cognitoUser object following successful authentication with aws-amplify

My Angular 11 project utilizes AWS Amplify (aws-amplify v3.3.26) with Cognito user pools for user management. The hosted UI is set up without any custom attributes. All necessary permissions for read and write are configured in the user pool. The code use ...

Can you explain the distinction between declaring type using the colon versus the as syntax?

Can you explain the variation between using the : syntax for declaring type let serverMessage: UServerMessage = message; and the as syntax? let serverMessage = message as UServerMessage; It appears that they yield identical outcomes in this particular ...

Sending data using AJAX and receiving it in PHP

After spending 3 days and coming across numerous basic questions in this community, I have finally managed to grasp a bit of the concept of ajax post. However, I am still stuck on one little issue - how can I retrieve the value passed by Ajax using PHP? $ ...

There was an issue with validating the initial certificate due to an error message stating "WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid

I have developed a spa application that generates tokens and now I need to validate these tokens in a web API. The application has been configured using the methods outlined in Azure's official documentation. Here is the link to the configuration app ...

The JSX element 'HeaderPublic' does not contain any construction or calling signatures

I am currently utilizing nx workspace to build the react ts application. Below is the library component: import { ReactElement } from 'react'; import styles from './header-public.module.scss'; export function HeaderPublic(): ReactElem ...

Using JSON response directly in loaded HTML in Angular 2 is a straightforward process. Follow these steps to

As I delve into Angular 2 and explore its components, one question that arises is how to display data received from a server in JSON format on an HTML page. In Angular 1.x, we could directly assign a JSON object to a variable and use it in HTML using the & ...

Angular 2: Issue with Input Controls losing value within a form element using ngFor

After developing a page in Angular2 that utilizes a form tag and renders input controls using ngFor within a table tag, I encountered an issue where selected input values are removed upon adding a new row. However, everything works fine when the form tag i ...

How can you add or remove an item from an array of objects in Angular/RXJS using Observables?

Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step. NewObject.ts: export class NewObject { name: string; title: string; } Here's the example ...

How to automatically redirect in Angular 2 by utilizing router.navigate

router.navigate() seems to be working correctly in one scenario, but in another case it is redirecting to the home page unexpectedly. app.module.ts const appRoutes: Routes = [ { path: 'news/:urlLink', component: ArticlereaderComponent }, ...

Stop automatic variable updates in Angular

In Angular, variable x is assigned to variable y. Whenever variable x changes, y also gets changed. How can this behavior be prevented? ngOnInit() { this.editFunction() } editFunction(){ for (let i = 0; i < this.editingData["tags"].length; i ...

Having trouble retrieving data from mongo db collection - data not found

For my eCommerce application, I am using MongoDB and Angular. The requirement is to retrieve items under each user in the cart. However, when trying to fetch the data using the object ID as a reference, it seems unable to find any data from the database. ...

Unable to locate TypeScript declared class

I have extended a class that inherits from the EventEmmiter class. For better support and auto-completion in IntelliSense, I wanted to display the available events to listen to. Here is my solution: //Imports from index.ts import { CommandContext, ...

Understanding Restangular with Typescript can be challenging, especially when dealing with a 'restangularized' response object

In my project, I am working with Angular 1.5.x using TypeScript in combination with restangular to access a remote API. Here is an overview of the scenario: The API endpoint I am connecting to is http://localhost:53384/api/timezones. Making a GET request ...

Issue with Angular app using Azure AD not redirecting to specified path after successful login

My angular webapp is connected to Azure AD/Entra Id for user authentication. The redirect URI in my Azure AD app is set as "http://localhost:4200/translate". Here are my defined routes: const routes: Routes = [ { path: 'translate', path ...

Transferring various sets of information into a single array

In an attempt to generate JSON data in an array for passing to another component, I followed a method outlined below. However, being relatively new to this field, my execution may not have been optimal as expected. employeeMoney: any[] = []; employeeId: an ...

Message within the boundary of the input field

Click here to view the image It would be great to have the text "text name" displayed on the border of the input box. Here is the HTML code - <input type="text" id="text creator" class="form-control" placeholder="text creator" na ...