【问题标题】:Angular HttpClient request method how to set bodyAngular HttpClient请求方法如何设置正文
【发布时间】:2019-06-09 08:26:01
【问题描述】:

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

我能够在没有正文部分的情况下从下面的示例中获取数据,但我确实需要以 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'
        });
}

【问题讨论】:

  • 如您所说,GET 请求中没有正文。 request 不会改变这一点:get 只是 request('GET') 的简写。
  • 我认为您正在寻找的是POST 请求,请查看angular.io/guide/http#making-a-post-request
  • 感谢您的回复。你能告诉我 URL 是否在 REST 标准中吗? /api/subscribers/?id=key1,op1,value1&name=key2,op2,value2 我认为这样我也可以解决我的问题

标签: angular angular-httpclient


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    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 端点。

    谢谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      相关资源
      最近更新 更多