Mitul Panchal
Mitul Panchal

Reputation: 283

Angular Http GET call pass array as params to API

Hi I'm new to angular hence got stuck at one place. I need to pass array as parameters to backend API backend API expects array of string as parameters

 const params = new HttpParams();
 const depKey = ['deploymentInprogress', 'deploymentMessage'];
 params.append('depKey', JSON.stringify(depKey));

 this.http.get(uri, { params: params })
      .pipe(
        take(1),
        catchError((error) => {
          return throwError(error);
        })
      ).subscribe(data => {

   })
 

The above code didn't work Need an help on this I'm not sure how we can pass array of strings as params to our backend API

Upvotes: 0

Views: 2438

Answers (3)

FedG
FedG

Reputation: 1301

You can do this:

const params = new HttpParams();
 const depKey = ['deploymentInprogress', 'deploymentMessage'];
 params.append('depKey', depKey.join(', ');

 this.http.get(uri, { params: params }).....

Upvotes: 2

Charlie V
Charlie V

Reputation: 1040

You need to know what the specification of the backend API is. Without the specification it's just guessing how to get this to work.

Most of the times it will be encoded in the body and that can be done in may forms, for example:

{ 
   "key": "value",
   "items": [
      {"aaa":"bbb","ccc":"dddd"},
      {"aaa":"fff","ccc":"hhhh"}
   ]
}

but note: this is just one way of doing it!

If you can share your specifications, we can help you.

Maybe you have a postman example on how to call the endpoint?

Upvotes: 0

Naren Murali
Naren Murali

Reputation: 58492

You can send the array values individually with the same parameter name, then api can read the individual values!

 const params = new HttpParams();
 const depKey = ['deploymentInprogress', 'deploymentMessage'];
 depKey.forEach((item: any) => {
     params.append('depKey', item);
 });

 this.http.get(uri, { params: params })
      .pipe(
        take(1),
        catchError((error) => {
          return throwError(error);
        })
      ).subscribe(data => {

   })

Upvotes: 0

Related Questions