angularangular-httpclienthttp-parameters

Not able to pass parameter in POST url angular


Hi I am trying to pass parameter in POST method url in angular service to construct a URL to fetch some data from an API but when I am calling it on component file I am getting error response.

Where am I doing wrong ?

Example I need this type of url to pass:- https://something/api/v1/map/GetdetailsById?ID=EF-345-RHDJI34-EHI3

In service I am doing :-

// Http Options
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

//POST API to show lists
  getOTList(): Observable<any> {
    const params = new HttpParams()
    .set('ID', 'EF-345-RHDJI34-EHI3');
    return this.http
      .post<any>(`${environment.Url}` + `${APIs.getList}`,{params}, this.httpOptions)
      .pipe(
        retry(1),
        catchError(this.handleError)
      )
  }

Ang in component I am doing :

ngOnInit(){
    this.getLists();
  }

getLists(){
    this.addService.getOTList().subscribe((response:any) => {
      if (response.IsSuccess == true) {
        console.log(response);
      }
      else {
        console.log("something is wrong.") //<========== getting this message in console
      }
    });
  }

Solution

  • We are doing a POST request, therefore we need to add a body. Your params should also be set into the same object as your httpOptions, setting the content type to json is really not needed with the HttpClient, it happens automagically, so I would just do:

    return this.http.post<any>(`${environment.Url}` + `${APIs.getList}`, {}, { params })
    

    Notice the empty body {}. As you are not even passing a body, this wouldn't need to be a POST request, just thought I'd mention. Also, please don't use any. Typing your data will help you in the future! :)