Sending string arrays as parameters in Angular HTTP GET requests

Hey everyone! I’m a beginner with Angular and I’m having trouble figuring out how to send an array of strings as parameters in an HTTP GET request. My backend API needs to receive this array, but I can’t seem to get it working. Here’s what I’ve tried so far:

const params = new HttpParams();
const statusKeys = ['inProgress', 'statusMessage'];
params.append('statusKeys', JSON.stringify(statusKeys));

this.http.get(apiUrl, { params: params })
  .pipe(
    take(1),
    catchError((err) => throwError(err))
  ).subscribe(response => {
    // Handle response
  });

This code doesn’t seem to work as expected. Can anyone point me in the right direction on how to properly send an array of strings as parameters in an Angular HTTP GET request? I’d really appreciate any help or advice. Thanks in advance!

I’ve run into this exact problem before, and I found a solution that works well. Instead of using HttpParams, you can directly add the array to the request options like this:

const options = {
  params: {
    statusKeys: statusKeys
  }
};

this.http.get(apiUrl, options)
  .pipe(
    take(1),
    catchError((err) => throwError(err))
  ).subscribe(response => {
    // Handle response
  });

Angular’s HttpClient will automatically serialize the array for you. On the server side, you’ll receive the array as repeated query parameters, like ?statusKeys=inProgress&statusKeys=statusMessage. This approach is clean and works out of the box with most backend frameworks. Just make sure your API is set up to handle multiple values for the same parameter name.

If you need a different format, you might have to serialize the array manually before sending it. But in most cases, this method should do the trick without any extra steps.

I encountered a similar issue in one of my projects. The solution that worked for me was using HttpParams.fromObject() to create the parameters. Here’s how you can modify your code:

const params = new HttpParams().fromObject({
  statusKeys: statusKeys
});

this.http.get(apiUrl, { params })
  .pipe(
    take(1),
    catchError((err) => throwError(err))
  ).subscribe(response => {
    // Handle response
  });

This approach automatically serializes the array for you. Just ensure your backend can handle array parameters correctly. If it expects a specific format, you might need to adjust accordingly. Also, don’t forget to import HttpParams from ‘@angular/common/http’.

hey, i’ve dealt with this before! try using params.set() instead of append(). also, you might wanna encode the array like this:

params = params.set('statusKeys', statusKeys.join(','));

this way, it’ll be sent as a comma-separated string. hope this helps!