1

嗨,我正在尝试在角度服务中的 POST 方法 url 中传递参数以构造一个 URL 以从 API 获取一些数据,但是当我在组件文件上调用它时,我得到了错误响应。

我在哪里做错了?

示例我需要通过这种类型的 url:- https://something/api/v1/map/GetdetailsById?ID=EF-345-RHDJI34-EHI3

服务中我正在做:-

// 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 :

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
      }
    });
  }
4

2 回答 2

2

我们正在做一个 POST 请求,因此我们需要添加一个正文。您的参数也应该设置为与您的 httpOptions 相同的对象,HttpClient 确实不需要将内容类型设置为 json,它会自动发生,所以我会这样做:

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

注意空的身体{}。因为你甚至没有传递一个身体,所以这不需要是一个 POST 请求,只是想我会提到。另外,请不要使用any. 输入您的数据将在未来为您提供帮助!:)

于 2021-12-03T18:29:54.713 回答
0

您需要params在 http.post 调用中将 const 设置为 params 对象,如下所示{params: params}

所以你更新的服务功能应该是这样的:

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)
      )
}
于 2021-12-03T17:08:31.087 回答