Hola, estoy tratando de pasar el parámetro en la URL del método POST en el servicio angular para construir una URL para obtener algunos datos de una API, pero cuando lo llamo en el archivo del componente, recibo una respuesta de error.
¿Dónde estoy haciendo mal?
Ejemplo, necesito este tipo de URL para pasar: - https://something/api/v1/map/GetdetailsById?ID=EF-345-RHDJI34-EHI3
En el servicio que estoy haciendo: -
// 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 en el componente que estoy haciendo:
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 } }); }Estamos haciendo una solicitud POST, por lo tanto, necesitamos agregar un cuerpo. Sus parámetros también deben configurarse en el mismo objeto que sus httpOptions, establecer el tipo de contenido en json realmente no es necesario con HttpClient, sucede automáticamente, así que simplemente haría:
return this.http.post<any>(`${environment.Url}` + `${APIs.getList}`, {}, { params }) Observe el cuerpo vacío {} . Como ni siquiera está pasando un cuerpo, esto no necesitaría ser una solicitud POST, solo pensé en mencionarlo. Además, por favor, no uses any . ¡Escribir tus datos te ayudará en el futuro! :)
Debe configurar sus params const en el objeto params en su llamada http.post, así: {params: params} .
Entonces, su función de servicio actualizada debería verse así:
getOTList(): Observable<any> { const params = new HttpParams() .set('ID', 'EF-345-RHDJI34-EHI3'); return this.http.post<any>(`${environment.Url}` + `${APIs.getList}`, {params:params}, this.httpOptions) .pipe( retry(1), catchError(this.handleError) ) }