Enhancing the basic HTTP request Observable method

I am working with restaurant objects and have a method that returns all restaurants from the database:

    getRestaurantAll() : Observable<Restaurant[]>
    {
      return this.http.get<Restaurant[]>(`${this.baseUrl}api/Restaurant`)
        .pipe(
          catchError(this.handleError<Restaurant[]>(`getRestaurantAll`,[]))
        );
    }

Now, I want to create a similar method with a small modification. The important array properties of Restaurant are TypesOfFood (Pizza, Burgers, Tacos, Ramen) and MethodsOfPayment (Credit, Debit, Cash, Vouchers).

Currently, the user's selections are stored in string variables as userFoodChoice and userPaymentChoice.

I aim to show the user a list of Restaurants that accept both food and payment choices simultaneously.

How can I adjust the above request to filter only the Restaurants that match both of the users' selections?

Answer №1

It is recommended to handle this control logic on the backend rather than the frontend, allowing for a list of restaurants that match users' preferences to be directly generated from the backend. However, if you prefer to implement it on the frontend, you can utilize the map function in the following manner:

return this.http.get<Restaurant[]>(`${this.baseUrl}api/Restaurant`)
    .pipe(
      map((res: Restaurant[]) => {
         const filteredRestaurants = res.filter(
            (restaurant) => {
              // Include your conditions here
            });
         return filteredRestaurants;
      }),
      catchError(this.handleError<Restaurant[]>(`getRestaurantAll`,[]))
    );

Answer №2

If you're looking to narrow down your selection based on specific elements from two arrays, simply retrieve the values you want to filter by (such as filteredTypesOfFood and filteredMethodsOfPayment) and use them as the basis for your filtering logic.

filteredTypesOfFood = 'Pizza';
filteredMethodsOfPayment = 'Credit';

...
return this.http.get<Restaurant[]>(`${this.baseUrl}api/Restaurant`)
    .pipe(
      map((res: Restaurant[]) => {
         const filteredRestaurants = res.filter(
            (restaurant) => {
              return (restaurant.type === this.filteredTypesOfFood
                     || restaurant.method === this.filteredMethodsOfPayment);
            });
         return filteredRestaurants;
      }),
      catchError(this.handleError<Restaurant[]>(`getRestaurantAll`,[]))
    );

For a simplified example showcasing how this can work using a mock array of restaurants, check out this functional demo: https://stackblitz.com/edit/angular-restaurant-filtered-array?file=src/app/app.component.ts

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

The 'React' namespace does not contain the exported members 'ConsumerProps' or 'ProviderProps'

Is it possible to install this library in Visual Studio with React version 15.0.35? Are there any other libraries that are compatible with this specific React version? import * as React from 'react'; import { RouteComponentProps, NavLink } from ...

Error 404: The requested resource could not be located on the server running nginx with Angular version 8

Encountering an issue where trying to access `mywebsiteurl/radar-input` or `mywebsiteurl/daily-submissions` results in a `404 Not Found` error. The components load correctly without using the routing method, indicating the problem might lie there. Below is ...

Using ng-bootstrap with Bootstrap 4 beta as an npm dependency

After updating my npm dependencies in package.json to Bootstrap 4 beta and ng-bootstrap to 1.0.0-beta.5, I encountered an "UNMET PEER DEPENDENCY" for popper.js when running npm install due to its new addition as a dependency in Bootstrap 4 beta. Despite th ...

Navigating with Angular 2 routing

In my Angular 2 typescript application, I have defined routes as follows: @RouteConfig([ { path: '/accounts', name: 'Accounts', component: AccountComponent, useAsDefault: true}, { path: '/transactions', name: ...

When authentication is successfully completed, proceed to the designated URL

Currently in the process of developing a project for educational purposes, utilizing Angular16 and Supabase as the backend technology. I have successfully implemented user sign-ins with Github, Google, and email (the method used for signing in doesn't ...

Troubleshooting: TypeScript not functioning properly with Create Next App dev server启动时有问题

When I attempted to set up a nextjs+typescript app using the command npx create-next-app@latest --ts, all the installations went smoothly. However, upon running the dev function, I encountered an error related to Global CSS. error - ../../../#Typescript/Ne ...

"Utilizing mongoDb's $set and $setOnInsert directives for updating specific fields within nested properties

I have a file containing sub-categories { a: fire, b: { plane: fly, c: swim, d: jump, } } During upserts, I want to specifically change the "plane" category. Here is what I have attempted: const { categories, ...rest } = newRecord; cons ...

What purpose does the Angular core module serve?

I recently came across an interesting blog post discussing the organization of folders in Angular. The author suggests using a folder called core, within which only services that are called once are placed. Implementing the recommended structure, I create ...

Tips for Showing an Image on an HTML Page Offline

I am facing a challenge where I need to display an image without relying on an internet connection and without storing the image in cookies. My initial attempt was placing the image URL in the head section using a link tag. <head> <title>@ ...

Building a personalized React component poses challenges when working with MUI REACT interfaces

I am looking to develop a unique component that will display two different elements, an icon, and a title. However, I seem to be encountering errors from TypeScript regarding the declaration of my interface. The error message reads: Property 'map&apos ...

How can I redirect a page using an axios interceptor in Next.js?

Is there a way to redirect the page in an axios interceptor when dealing with server-side rendering limitations? Unfortunately, I am unable to access the server side context in the axios interceptor. I have tried using next/router but it only works on the ...

Deployment of Typescript.js files in Angular 2

Do you think it's practical to gulp-typescript the typescript files into js files for deploying on a webserver, considering that the Angular2 quickstart guide requires a typescript-1.x.x.js file that is around 2.9MB in size, even when minified? ...

Sync up the Microsoft Access database with the database of the Silverstripe website

One of my clients has an existing website that manages membership details, member portfolios, and directories manually using php with the Silverstripe CMS platform. In addition, their admin person also maintains an offline member data system in Microsoft A ...

arranging multiple popular columns in an ng-template for an angular table

Incorporating angular 15.1 with angular material, I am utilizing the angular material Table component to present tables. Within my project, there are approximately 20 distinct tables that share 90% of the column definitions. As a result, I aim to centrali ...

Comparison: executing an immediately invoked function expression (IIFE) and a separate

During my recent refactoring of some legacy code, I stumbled upon the following example: // within another function const isTriggerValid = await (async () => { try { const triggers = await db.any(getTriggerBeforeBook, { param ...

Difficulty with Bootstrap Carousel (image is displayed but fails to transition/change)

Although I don't have much experience in this, I've searched through various documentations and solutions that have helped others. Unfortunately, I haven't been able to fix my issue, so I decided to create my own post to seek assistance. &l ...

Compiling Typescript upon saving in Sublime Text 3

Seeking a solution: How can I get Sublime Text 3 to automatically compile Typescript code when I save it? Having to switch between the terminal and Sublime is getting tedious. Appreciate any advice, thank you! ...

What is the process in TypeScript for defining a custom variation of a generic function?

Suppose we have a generic function: const f1 = <T>(x: T) => console.log(x) We can then create a specialized version for f1, like this: const f2 = (x: number) => f1(x) If we try to call f2 with an argument of type string, TypeScript will thr ...

Troubleshooting Cors Problem between Angular 2 Form Data and Express

I'm attempting to send some files to an Express server that utilizes the cors() module in the following way app.use(cors()); This is the Angular 2 code used for file uploading let formData:FormData = new FormData(); for(let i = 0; i < files. ...

Guide to making a prop optional in reactjs with the help of typescript

Issue: I have a parent component and reusable component. The reusable component is used twice within the parent component. When passing a boolean prop named 'visible' to one of the instances of the reusable component, PyCharm throws an error stat ...