简体   繁体   中英

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

You can do this:

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

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

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

   })

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM