Angular HttpClient请求方法如何设置body

Angular HttpClient request method how to set body

我需要发送一个带正文的获取请求。我正在使用 angular HttpClient。我知道 get 方法不允许发送正文,所以我尝试使用请求方法,但我不明白如何使用它。

我能够从没有正文部分的示例波纹管中获取数据,但我确实需要以 JSON 格式发送正文。

    request(req?: any): any{

    const options = createRequestOption(req);
    return this.http
        .request<ISubscriber[]>("GET", this.resourceUrl,
        {
            body: '[{"key": "phoneLineType", "operation": ">", "value": "200"}]',
            headers: new HttpHeaders({'Content-Type' : 'application/json'}),
            params: options,
            observe: 'response'
        });
}

使用 http.get() 只是 http.request('GET') 的 shorthand。如果您真的需要发送 JSON 正文,那么您将不得不使用另一种类型的请求 - 例如 post。您可能需要这样的东西:

return this.http
  .post<ISubscriber[]>(
    this.resourceUrl,
    '[{"key": "phoneLineType", "operation": ">", "value": "200"}]',
    {
      params: options
    {
  )

您可能需要更改 API 端点以期待不同的 HTTP 动词。

我听从了您的建议,这是我以后为其他人提供的解决方案...

queryPost(body: string, req?: any) : any {

    const options = createRequestOption(req);
    return  this.http.post<ISubscriber[]>(this.searchUrl, body,
            {
                headers : new HttpHeaders({"Content-Type": "application/json"}),
                params: options,
                observe: 'response'
            });
}

同样提到我必须在我的后端应用程序中创建一个新的 Post 端点。

谢谢大家