简体   繁体   English

使用 Angular 的 HTTPClient 在 API 请求的可重用 function 中确定适当的 HTTP 方法

[英]Determine the appropriate HTTP method in a reusable function for API requests using Angular's HTTPClient

I want to implement a reusable service for making requests to my API.我想实现一个可重用的服务来向我的 API 发出请求。

Right now, I have it working as intended, but for GET requests only.现在,我让它按预期工作,但仅适用于GET请求。

Here's the function:这是 function:

  makeAPIRequest = ({ ...opts }) => {
    return this.http.get(opts.url, opts.params)
      .toPromise()
      .then(response => response)
      .catch(err => this.handleError(err));
  };

And here's an example of how it's being used:这是一个如何使用它的例子:

  getCustomer(id): Promise<Customer> {
    return this.APIService.makeAPIRequest({
      url: this.customerEditUrl(id)
    }) as Promise<Customer>;
  }

I want to extend the functionality such that I'm able to pass an HTTP method into opts , but I'm not sure how to do that cleanly.我想扩展功能,以便能够将 HTTP 方法传递给opts ,但我不确定如何干净地做到这一点。 I'd like to avoid using a large conditional and repeating myself -- it'd be nice to be able to approach this concisely.我想避免使用大的条件并重复自己——能够简洁地处理这个问题会很好。 For example, if I pass in opts that look like this:例如,如果我opts如下所示的选项:

 { url: this.customerEditUrl(id), params, httpMethod: 'POST' }

How can I make my makeAPIRequest function look like this?如何使我的makeAPIRequest function 看起来像这样?

  makeAPIRequest = ({ ...opts }) => {
    return this.http.post(opts.url, opts.params)
      .toPromise()
      .then(response => response)
      .catch(err => this.handleError(err));
  };

Thanks in advance!提前致谢!

Instead of using this.http.post() you could manually create a new request.您可以手动创建一个新请求,而不是使用this.http.post() The request constructor allows specifying the method as a string.请求构造函数允许将方法指定为字符串。

Have a look at: https://angular.io/api/common/http/HttpClient#request看看: https://angular.io/api/common/http/HttpClient#request

One of the constructor overloads for this.http.request(...) looks as follows: this.http.request(...)的构造函数重载之一如下所示:

request(method: string, url: string, options: { body?: any; headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType: "blob"; withCredentials?: boolean; }): Observable<Blob>

As you can see the first parameter is the HTTP Method as string.如您所见,第一个参数是 HTTP 方法作为字符串。 The rest should be relatively familiar to you. rest大家应该比较熟悉。

this.http.request(opts.httpMethod, opts.url, opts.params)

should do the trick;)应该做的伎俩;)


I also suggest you have a look at using observable directly instead of converting the returned observable to a promise.我还建议您看看直接使用 observable,而不是将返回的 observable 转换为 promise。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM