How to conceal an empty array in POST requests using Angular 2

When filtering products, I would like to send the array only if it contains elements. Is this possible?

Request function:

getRecipes(page, pageSize, filters){
let body = JSON.stringify({ "size": pageSize, "page": page, "listOfFilters": filters});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

return this.http.post('http://localhost:8080/cookbook/recipe/filter',body,options)
        .map((res: Response) => res.json());}

Filter Class:

export class Filter{
    products = new Array<String>();
    rating: {[key: string]:string} = {};
    level: {[key: string]:string} = {};
}

The current JSON format is:

{"size":10,"page":1,"listOfFilters":{"products":[],"rating":{"from":"1","to":"5"},"level":{"from":"1"
,"to":"5"}}}

I would like it to be like this (when the products list is empty):

{"size":10,"page":1,"listOfFilters":{"rating":{"from":"1","to":"5"},"level":{"from":"1"
    ,"to":"5"}}}

Answer №1

I'm unsure about the exact desired outcome, but here is a simple use of an if statement with the JavaScript delete method.

if (filters.products.length == 0) {
        delete filters.products;
    }
    
    let body = JSON.stringify({ "size": pageSize, "page": page, "listOfFilters": filters });
    

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

Problems encountered with cordova-plugin-facebook4 in Ionic 2

I'm encountering the following error: Error: Metadata version mismatch for module /opt/lampp/htdocs/www/ionicApp/node_modules/@ionic-native/facebook/index.d.ts, found version 4, expect when running the command: ionic cordova run android --prod --rel ...

Encountering a NgForm provider error in Angular 4.4.6 development mode

UPDATE: Identifying the root of the issue has led me to search for a suitable solution. NOTE: This complication is specific to development mode (not production, and not utilizing AOT). The "Update" resolution I am implementing can be found here. In an a ...

Having trouble with Apple Login functionality in Safari on my Angular application

While implementing apple login in my web app, I encountered an issue with Safari browser. Instead of opening the redirect URI in a new tab, it displays a finger touch enabled login popup. This prevents the passing of the redirect URI and causes problems wi ...

Resolving Hot-Reload Problems in Angular Application Following Upgrade from Previous Version to 17

Since upgrading to Angular version 17, the hot-reload functionality has been causing some issues. Despite saving code changes, the updates are not being reflected in the application as expected, which is disrupting the development process. I am seeking ass ...

Include a thousand separator and round to two decimal places in the ngModel input

I have been attempting to format my input values by adding thousand separators and 2 decimals as shown below TS onBlur(event){ if (event.target.value !== ''){ event.target.value = (parseFloat(event.target.value).toFixed(2)).toLocaleS ...

Creating TypeScript projects without the use of a conventional IDE or text editor

Due to restrictions in my workplace, I am unable to download or install any applications, regardless of my job duties. I am interested in migrating several web apps to Angular 2 using TypeScript. I am a C# developer in my free time and I find TypeScript ap ...

Embracing PWAs with subdomains – seamless installation

One of my Progressive Web Applications (PWA) called app A contains a link to another app, app B. Initially, I hosted both apps on the same subdomain (for example: ) and everything worked perfectly - installing app A also installed app B. However, when I a ...

I am in search of a method to rephrase the content while minimizing redundancy

I am looking to improve the code for handling two different conditions in the UI. Can someone suggest a better way to rewrite it? <i *ngIf="measures.length > 0"> <ul *ngFor="let m of measures"> <io-data-selection-row [text] ...

Solutions for resolving the issue of not being able to load images when using merged-images in JavaScript

I have a base64 image here and it has already been converted. data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQSEhUTEhQWFhUXGBoaGBgYGBcXGhgXGBgYGhgbHhoZHiggGholHhgYITEhJSkrLi4uHR8zODMtNygtLisBCgoKDg0OGhAQGi0lICUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0 ...

Executing Scripts inside an iFrame in Angular

Upon receiving an API response, I am presented with HTML as a string. Inside this HTML are internal script tags that contain functions called under $(window).load(). How can I successfully load this HTML within my Angular app? I attempted to append the HT ...

Exploring the location of unit testing within async-await in Angular applications

I have been working with Angular 9+ along with karma test runner and jasmine test framework for my unit tests. My focus is on unit testing only the app component which includes dependency injection: app.component.ts import { Component, EmbeddedViewRef } ...

The link in the navbar isn't functioning properly, which indicates that it's not redirecting to the specified ID on this one-page application

<!-- NAVBAR --> <nav class="navbar navbar-expand-lg py-3 sticky-top navbar-light bg-white"> <div class="container-fluid"> <a class="navbar-brand" href="#acasa"> <img class="logo" src="./assets/img/xxxxx_psiholog_logo. ...

What is the process for removing a specific column (identified by its key value) from a JSON table using JavaScript and Typescript?

[{ "name": "employeeOne", "age": 22, "position": "UI", "city": "Chennai" }, { "name": "employeeTwo", "age": 23, "position": "UI", "city": "Bangalore" } ] If I remove the "Position" key and value from the JSON, the updated r ...

Issues with implementing Angular Material's MatDialog functionality in Angular-6 were encountered

I'm just getting started with Angular and Angular Material, and I attempted to use MatDialog. I followed the given instructions, but unfortunately, it did not work for me. Here is the MatDialog Overview. Does anyone know the correct way to utilize M ...

Whenever I attempt to launch the application on my device, an error message stating "plugin_Not_Installed Exception" occurs

I encountered a plugin_Not_Installed Exception when running the app on my device. Here are the details of my Ionic setup: Ionic: Ionic CLI : 5.4.16 Ionic Framework : @ionic/angular 6.2.2 @angular-devkit/build-angular : 1 ...

Is there a way to automatically scroll 50 pixels down the page after pressing a button?

Is there a way to make my page scroll down in Angular when a button is clicked? I attempted to use this code, but it didn't have the desired effect. What is the best method for scrolling the page down by 50px? window.scrollBy(0, 50); ...

Lazy loading in Angular allows you to navigate directly to a certain feature component

I'm currently working on implementing lazy loading in Angular 6, and I want to include links on my main homepage that direct users to specific feature components. Here is the hierarchy of my project: app.module.ts |__homepage.component.ts |__options ...

What is the process for setting up a callback function in material-angular-select?

It's surprising that I couldn't find an onselect callback for the material-angular-select component. How can I create a callback for it? Here is my attempt: import { Component, Input, Output, OnInit, OnChanges, SimpleChanges, ChangeDetectionStr ...

What is the best way to generate a type that generates a dot notation of nested class properties as string literals?

In relation to the AWS SDK, there are various clients with namespaces and properties within each one. The library exports AWS, containing clients like DynamoDB and ACM. The DynamoDB client has a property named DocumentClient, while ACM has a property call ...

After a recent deployment, the Angular PWA hosted on a NestJS server experiences unexpected crashes

I have set up an Angular PWA (version 11) on a NestJS (version 7) server. However, after each new deployment, the PWA crashes because the browser attempts to fetch a JavaScript file that no longer exists and then redirects to the root site (html): main.945 ...