Change the boolean value of a checkbox to text before including it in a GET request to send to an API

Currently, I am working on a school project that involves creating a recipe search application using Angular for the frontend and Laravel for the backend. The application fetches recipes from the Edamam API. I am looking to implement a feature where users can filter their searches using checkboxes and translate the "true" value to a specific text that I define in the search query. I have an object with checkbox properties that are initially set to false but change to true when checked.

My main questions are: How can I convert the true value to a text like "&dishType=starter"? and how do I determine if some of the properties in my object are true so I can append the corresponding text to my search query?

Below is the structure of my search form:

            <input id="search-box" type="text" (keyup.enter)="getRecipes()" [(ngModel)]="searchquery">
            <label for="starter" class="filter">
                <input class="filter-checkbox" type="checkbox" id="starter" [(ngModel)]="filter.starter">
                <span> Starter</span>
            </label>
            <label for="main" class="filter">
                <input class="filter-checkbox" type="checkbox" id="main" [(ngModel)]="filter.main">
                <span> Main</span>
            </label>
            <label for="dessert" class="filter">
                <input class="filter-checkbox" type="checkbox" id="dessert" [(ngModel)]="filter.dessert">
                <span class="checkbox-text">Dessert</span>
            </label>
 <button type="button" (click)="getRecipes();">Search</button>

Here is the object storing the checkbox values:

filter = {
    starter: false,
    main: false,
    dessert: false,
  };

Below is the function responsible for retrieving the recipes:

getRecipes() {
    this.loadRecipes = true; // Ignore
    this.recipeShow = false; // Ignore
    console.log(
      this.filter.starter,
      this.filter.main,
      this.filter.dessert,
    );
    this.recipeService
      .getRecipes(this.searchquery, // Here is where i want to put the filter values)
      .subscribe((result) => {
        this.recipeShow = true; // Ignore
        this.loadRecipes = false; // Ignore
        let searchedWord = this.searchquery; // Ignore
        let recipes = result.hits.map((data: any) => {
          let recipe = data.recipe;
          recipe.idref = data._links.self.href.slice(38, 70);
          return recipe;
        });
        
        this.allRecipes = recipes;
        
        this.word = searchedWord;
      });
  }

Lastly, here is the function in my recipe.service.ts file:

getRecipes(q: string, filter: string) {
    let searchquery =
      this.urlConfig +
      '?type=public&q=' +
      q +
      '&app_id=' +
      this.appid +
      '&app_key=' +
      this.appkey +
      filter +
      '&field=label' +
      '&field=idref' +
      '&field=image' +
      '&field=ingredientLines' +
      '&field=yield' +
      '&field=shareAs' +
      '&field=totalTime' +
      '&field=healthLabels' +
      '&field=dietLabels' +
      '&field=mealType' +
      '&field=dishType' +
      '&field=cuisineType';
    return this.http.get<any>(searchquery, this.httpOptions);
  }

Answer №1

If you need to change a boolean into a string, one way to do it is by using '' + booleanValue or 'someString=' + booleanValue.

However, it may not be necessary in this situation. Angular's HttpClient and Laravel can handle the conversions for you. Consider exploring how to send POST requests instead. Create an Object with all the required parameters and reflect that object in the backend.

For example, you could have something like this:

filterObject = {
  starter: false,
  main: false,
  dessert: false,
  field: ['label', 'image', ...],
};

Then, in the service, make the following call:

return this.httpClient.post<any>(
   `${this.urlConfig}/path-to-rest?api_id=1&api_key=2`, 
   filterObject
);

Ensure that you are using JSON format for both sending and receiving data.

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

Issue with Angular2 formBuilder: two validators are not functioning as expected

Need help with a text input that is required and must be longer than 3 characters. When clicking on the input, if a user types something shorter than 3 characters and then clicks out, a red border should be added. Otherwise, the border should be green. ...

Is it possible for a TypeScript definition file to include a require statement?

Can I include a statement like this in my definition file (.d.ts)? import foo = require('some-module/bar'); I believed this would automatically convert my definition file into a module. Surprisingly, it still works for me even without strict mo ...

2 entities - perform an action once both have successfully provided data

Upon calling this.pokojeService.pobierzPokoje() and this.pokojeService.pobierzTypyPokoi(), I subscribe to their respective observables. Once the data is retrieved, it is stored in this.pokoje and this.pokojeTypy variables. These two observables are crucia ...

Differences in Angular 2 Performance: Analyzing AOT and JIT Payloads

I'm still getting the hang of Angular 2, so feel free to correct me if I'm off base. Comparing Angular 1 and 2 in terms of the compiler: In Angular 1, the compiler is more general and dynamic, meaning that a single code is used for dirty checki ...

methods for sharing real-time data between parent and child components in Angular versions 2 and above

When working with Angular, we are familiar with parent to child communication using the @Input decorator. However, the challenge arises when we need to pass dynamic data from the parent to the child component. Imagine having a 'name' property def ...

Ultimate combo: React, TypeScript, and Vite for seamless imports!

Problem The issue I'm facing is related to my React app built with the command yarn create vite. I tried to switch to using absolute imports instead of "../../.." in my files, but unfortunately it doesn't seem to work in my React + Vi ...

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...

unable to retrieve the values of the rowdata in GridOption

ngOnInit(): void { this.fetchAllAnimeReviews(); } public fetchAllAnimeReviews(){ this.animeservice.getAllAnimeReviews() .subscribe( response => { this.Anime = response; this.gridOption = this.createGridO ...

Unable to spy on the second and third call using Jest

I'm having trouble using spyOn on the second and third calls of a function in my jest test I attempted to follow the documentation with this approach: it("should succeed after retry on first attempt failure", async () => { jest.spyOn(n ...

Experimenting with directive using jasmine

I've been working on this directive but I'm having trouble writing the jasmine test for it. Any suggestions? import { Directive, Output, EventEmitter, HostListener } from '@angular/core'; @Directive({ selector: '[ctrlKeys]&apos ...

Tips for modifying the width of the mat-header-cell in Angular

Is there a way to customize the mat-header-cell in Angular? I've been trying to change its width without success. Any suggestions would be greatly appreciated. <ng-container cdkColumnDef="name"> <mat-header-cell *cdkHeaderCellDe ...

Angular2 calendar and time selector

Having trouble setting up a date and time picker for my angular2 app. Can anyone provide assistance with this? I've experimented with the following methods: Ng2-datetime: I added it to the main app.module file: import { NKDatetimeModule } from &ap ...

The routing functionality in an Angular Element seems to be malfunctioning when used in a separate Angular project. Instead of displaying the expected routes, only the "<router-outlet></router-outlet>" tags are visible on the website

The current situation: Our team is facing the challenge of integrating multiple angular frontend micro-services into a single application. To achieve this, we have chosen to use the Angular-Elements approach which resulted in a large JS-file when exportin ...

Using Axios and Typescript to filter an array object and return only the specified properties

I'm currently working on creating an API to retrieve the ERC20 tokens from my balance. To accomplish this, I am utilizing nextjs and axios with TypeScript. However, I'm encountering an issue where the response from my endpoint is returning exces ...

Ways to identify a modification in ag-grid when there is an update in my row data while transitioning from one component to another

I am currently working on a project using angular6 implementing ag-grid to display data from an angular dialog box. With multiple teams contributing, each creating their own components, I have encountered a unique situation that I am struggling to resolv ...

Performance challenges with rendering SVG in ngFor due to the presence of a highly nested array structure - in

I'm currently developing a business application that requires me to dynamically render SVG images for displaying floor plans. The SVG elements are stored in a database and provided to the front-end in JSON format, allowing the graphics to be rendered ...

What happens when a typed Array in Typescript has an undefined property?

I've encountered an issue with a seemingly simple problem that's causing me quite the headache. The code snippet in question is provided below: interface IFoo{ ReturnFirstBarObject1(): string; FillBarArray(array: Array<Bar>): void; } ...

Enabling Full-Screen Mode in a Nativescript (Angular) Webview

As I work on developing the webview, I encountered a specific issue: I am unable to achieve fullscreen for an element or video. Visit Here for more information Various solutions have been attempted: Learn more here Embedded YouTube videos in Html/ ...

What is the best way to create an interactive experience with MapLibre GL in Full Screen mode?

Hello, I am seeking a solution to create a map with the interactive option set to false, but once in full screen mode, I need this parameter to be true. Do you have any suggestions or ideas on how to achieve this? const _map = new MapGL({ contai ...

What is the process for extracting TypeScript types from GraphQL query and mutation fields in order to get args?

I am experiencing difficulties with utilizing TypeScript and GraphQL. I am struggling to ensure that everything is properly typed. How can I achieve typed args and parent properties in Root query and mutation fields? For instance: Server: export interfa ...