Angular 11 passing HttpParams different from String type

  angular, typescript

I’m using Angular 11 and I’m trying to pass parameters to backend with right type (the type I need on the backend side) to my @GetMapping controller.

If I try to do:

getData(page: Number, firstId: Number, secondId: Number): Observable<AirpollData[]> {
  let params = new HttpParams();
  params = params.append('page', page);           // #1
  params = params.append('firstId', firstId);     // #2
  params = params.append('secondId', secondId);   // #3
  return this.http.get<MyObject[]>('data', { params: params });
}

I obtain for all 3 line (#1 ,2 and 3) the following error:

Argument of type 'Number' is not assignable to parameter of type 'string'

Instead if I try to pass parameter as @PathVariable instead of as @RequestParam as following:

getaData(firstId: Number, secondId: Number, page: Number): Observable<MyObject[]> {
 return this.http.get<AirpollData[]>('data/' + firstId+ '/' + secondId+ '/' + page);
}

It does half of the work.. if the parameter are set everything goes fine but if they are set to null:

this.service.getData(null, null, this.page).subscribe(success => {
  .....
});

I obtain an error on backend side:

Number format exception for String value "null"

Is there a way to do something like that?
Or I must cast all parameters I’m passing from String to something else?

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.