Using HttpParams to make a GET request in Angular

Here is the GET mapping in my backend:

@GetMapping(value = "search")
public List<Cat> search(@RequestBody CatDto catDto) {
    return catService.search(catDto);
}

I am trying to send a GET request to retrieve a list using Angular's HttpClient. Since GET requests cannot have a request body, I attempted the following in my component.ts:

search(cat: Cat): Observable<Cat[]> {
   let params = new HttpParams();
   params = params.append('name', cat.name);
   params = params.append('rating', (cat.rating).toString());
   params = params.append('birthday', (cat.birthday).toLocaleDateString());
   return this.httpClient.get<Cat[]>(this.messageBaseUri+'/search', {responseType: 'json', params});
}

However, I encountered the error:

Required request body is missing

Coming from my backend. Is there a way to achieve this without modifying my backend or do I need to change my backend endpoint as follows:

@GetMapping(value = "search")
public List<Cat> search(@RequestParam String name,
                        @RequestParam Integer rating,
                        @RequestParam Date birthday) {

    return catService.search(name, rating, birthday);
}

Answer №1

It seems like you are looking for the following information:

Java Controller:


            @GetMapping("/search")
            public List<Cat> search(
                                    @RequestParam("name") String name,
                                    @RequestParam("rating") Integer rating,
                                    @RequestParam("birthday") Date birthday) {
                       return catService.search(name, rating, birthday);
            }

Angular Service:


            searchCat(params: HttpParams): Observable<any> {
                return this.http.get<any>("/searchUrlHere", { params });
             }

To call the search Method with Parameters:


          onSearch(): void {
            const params = new HttpParams()
              .set('name', "yourName")
              .set('rating', "rating");
              .set('birthday', "birthday");
            this.goToSearchData(params);
          }

          goToSearchData(params: HttpParams) {
            this.catService.searchCat(params).subscribe(
              res => {
                console.log('List Data: ', res);
              },
              err => {
                console.log('Http error occurred');
              });
          }

OR


         onSearch() {
            const catParams = new HttpParams().set('name', "yourName").set('rating', "rating").set('birthday', "birthday");
            this.catService.searchCat(catParams).subscribe(
              resp => {
                  console.log('List Data: ', res);
              },
              err => {
                console.log('Http error occurred');
              });
          }

Answer №2

Typically, GET requests do not contain an HTTP body.

One way to improve your Back-End is by modifying it to accept request parameters instead of a request body. You can achieve this by implementing the following code:

@GetMapping(value = "search")
public List<Cat> search(CatDto catDto) {
    return catService.search(catDto);
}

Answer №3

When making GET requests, the parameters are included in the URL.

In the Controller:

public List<Cat> search(@RequestParam CatDto catDto) {
    return catService.search(catDto);
}

Within the ViewModel:

public class CatDto {
  String name;
  Integer rating;
  Date birthday;
}

Using Angular:

search(cat: Cat): Observable<Cat[]> {
  let params = {
    name: cat.name, // you can also try "catDto.name": cat.name
    rating: cat.rating.toString(),  // you can also try "catDto.rating": cat.rating.toString()
    birthday: cat.birthday.toLocaleDateString() // you can also try "catDto.birthday": cat.birthday.toLocaleDateString()
  }

  return this.httpClient.get<Cat[]>(this.messageBaseUri+'/search', {
    responseType: 'json',
    params: params
  });
}

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

Getting started with testing in Angular 2

When I first started coding my app, unit tests were not on my mind. Now, I realize the importance and need to write them. However, while attempting to write tests using Jasmine only, I encountered an error when trying to import components - "system is no ...

Challenge with Routing in Angular 2

I'm dealing with a route setup like this: path: 'something/:id/somethingElse' In my header.component.html, I need to include a link to this page. I tried the following approach: <a routerLink="['something',myIdThatIsDynamicO ...

Creating a loading spinner with the help of an rxjs BehaviorSubject

After creating a loading spinner component for my angular 4 application to display during AJAX calls, I encountered an issue when trying to implement it with a subscription to a BehaviorSubject. This question is similar to how to show a spinner until data ...

The label overlay for MatInput remains fixed within the input box in an Angular form

I've encountered an issue with some of my form fields where the field label doesn't move up to the top border of the field when you start typing in the input box. Instead, it remains in the middle of the box, causing the characters you type to ov ...

Uncomplicating RxJs Operators: Decoding switchMap and combineLatest

I currently have the following RxJS subscription : combineLatest([obs1$, obs2$]) .pipe( filter(val=>!!val[0] && !!val[1]), // ensuring no null values on both observables switchMap(([val1, val2]) => combineLatest([of(v1), getObs3$( ...

Using custom hooks in JSX triggers a TypeScript error when the returned component is accessed

i just created a custom hook // useDropdown.ts function useDropdown(defaultState: number, options: number[]) { const [state, setState] = useState(defaultState); function Dropdown({ name }: { name: string }) { return ( <> <sel ...

Tips for effectively passing navigation as props in React Navigation with Expo

How can I correctly pass navigation as props to another component according to the documentation? The navigation prop is automatically provided to each screen component in your app. Additionally, To type check our screens, we need to annotate the naviga ...

Troubleshooting Angular Build Errors: Integrating Three.js

Upon setting up a new Angular application and integrating three along with @types/three, I proceeded to create a basic component. However, upon executing ng build --prod, the following errors are displayed: ERROR in node_modules/three/src/core/BufferAttri ...

Angular - Eliminate objects from an array based on their index matching a value in a separate array

I am facing a challenge with an array of indices and an array of objects: let indices = [1,3,5] let objArray = [{name: "John"}, {name: "Jack"}, {name: "Steve"}, {name: "Margot"}, {name: "Tim" ...

Angular Form Template Unidirectional Data Binding Example

I'm facing a challenge with one-way binding to a default value in my HTML form. Within my component, I have a Connection string that is initially set from local storage: export class AuthAdminComponent implements OnInit { public authenticated = f ...

The error message displayed was "Unable to define the isMultiple property for Jasmine."

Encountering an issue in my test: Failed: Cannot set property 'isMultiple' of undefined The test script that I am using is fairly standard. Here's how it looks: beforeEach(() => { fixture = TestBed.createComponent(DropdownTypeah ...

Is there a way for me to steer clear of having to rely on the Elvis Operator?

Throughout my journey building my Angular 2 website, I've found the Elvis Operator to be a crucial element that makes everything possible. It seems like every task I undertake involves mastering how to apply it correctly in every instance where data i ...

What causes the lack of impact on lambda rendering speed despite integrating webpack?

Hey there, I've been working on implementing webpack for a project that involves microservices, Node.js, TypeScript, AWS, and AWS SAM. My main objectives are: Reduce the cold start time of lambda functions. Minimize security vulnerabilities by e ...

What's the process for validating i18n dictionaries using TypeScript?

Is there a way to enforce type checking on existing keys within dictionaries in react-i18next? This means that TypeScript will provide warnings at compile time if a key does not exist. For example: Let's say we have the following dictionary: { "f ...

Issue with React useCallback not being triggered upon a change in its dependencies

useCallback seems to be capturing the wrong value of its dependency each time. const [state, setState] = React.useState(0); const callback = React.useCallback(() => { console.log(state); // always prints 0, why? }, [state]); React.useEffec ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

Ways to substitute a null value in ngFor

When the item value is null, an error occurs in the console and the functionality stops working. How can I verify or replace the null value with my own preferences? this.xx = this.broadCastService.events.subscribe((line: Line) => { this.configService ...

Using Threejs to create an elbow shape with specified beginning and ending radii

I'm a beginner in Threejs and I'm attempting to create an elbow shape along a curved path with varying begin_radius and end_radius, using the curve_radius and an angle. However, I haven't been successful in achieving the desired results. C ...

Customizing a generic method in typescript

I am currently working on developing a base class called AbstractQuery, which will serve as a parent class to other classes that inherit from it. The goal is to override certain methods within the child classes. class AbstractQuery { public before< ...

Mapping the preselected values of multiple input fields into an array in Angular 6: A step-by-step guide

When submitting a form with input fields, I need to capture the selected values into an array format like {"userid":1,"newstatus":[1],"mygroup":[1,2,3]}. I attempted using ngmodel but encountered issues. Below is the code snippet: home.component.html & ...