Home > Software design >  Angular Http GET call pass array as params to API
Angular Http GET call pass array as params to API

Time:12-14

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

CodePudding user response:

You can do this:

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

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

CodePudding user response:

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 => {

   })

CodePudding user response:

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?

  • Related