How to Make HTTP Requests

About HttpClient

Angular has the amazing HttpClient for communication with backend services. It is a layer on top and a simplified representation of XMLHttpRequest Web API. It also is the recommended agent by Angular for any HTTP request. There is nothing wrong with using the HttpClient in your ABP project.

However, HttpClient leaves error handling to the caller (method). In other words, HTTP errors are handled manually and by hooking into the observer of the Observable returned.

  1. getConfig() {
  2. this.http.get(this.configUrl).subscribe(
  3. config => this.updateConfig(config),
  4. error => {
  5. // Handle error here
  6. },
  7. );
  8. }

Although clear and flexible, handling errors this way is repetitive work, even when error processing is delegated to the store or any other injectable.

An HttpInterceptor is able to catch HttpErrorResponse and can be used for a centralized error handling. Nevertheless, cases where default error handler, therefore the interceptor, must be disabled require additional work and comprehension of Angular internals. Check this issue for details.

RestService

ABP core module has a utility service for HTTP requests: RestService. Unless explicitly configured otherwise, it catches HTTP errors and dispatches a RestOccurError action. This action is then captured by the ErrorHandler introduced by the ThemeSharedModule. Since you should already import this module in your app, when the RestService is used, all HTTP errors get automatically handled by deafult.

Getting Started with RestService

In order to use the RestService, you must inject it in your class as a dependency.

  1. import { RestService } from '@abp/ng.core';
  2. @Injectable({
  3. /* class metadata here */
  4. })
  5. class DemoService {
  6. constructor(private rest: RestService) {}
  7. }

You do not have to provide the RestService at module or component/directive level, because it is already provided in root.

How to Make a Request with RestService

You can use the request method of the RestService is for HTTP requests. Here is an example:

  1. getFoo(id: number) {
  2. const request: Rest.Request<null> = {
  3. method: 'GET',
  4. url: '/api/some/path/to/foo/' + id,
  5. };
  6. return this.rest.request<null, FooResponse>(request);
  7. }

The request method always returns an Observable<T>. Therefore you can do the following wherever you use getFoo method:

  1. doSomethingWithFoo(id: number) {
  2. this.demoService.getFoo(id).subscribe(
  3. foo => {
  4. // Do something with foo.
  5. }
  6. )
  7. }

You do not have to worry about unsubscription. The RestService uses HttpClient behind the scenes, so every observable it returns is a finite observable, i.e. it closes subscriptions automatically upon success or error.

As you see, request method gets a request options object with Rest.Request<T> type. This generic type expects the interface of the request body. You may pass null when there is no body, like in a GET or a DELETE request. Here is an example where there is one:

  1. postFoo(body: Foo) {
  2. const request: Rest.Request<Foo> = {
  3. method: 'POST',
  4. url: '/api/some/path/to/foo',
  5. body
  6. };
  7. return this.rest.request<Foo, FooResponse>(request);
  8. }

You may check here for complete Rest.Request<T> type, which has only a few chages compared to HttpRequest class in Angular.

How to Disable Default Error Handler of RestService

The request method, used with defaults, always handles errors. Let’s see how you can change that behavior and handle errors yourself:

  1. deleteFoo(id: number) {
  2. const request: Rest.Request<null> = {
  3. method: 'DELETE',
  4. url: '/api/some/path/to/foo/' + id,
  5. };
  6. return this.rest.request<null, void>(request, { skipHandleError: true });
  7. }

skipHandleError config option, when set to true, disables the error handler and the returned observable starts throwing an error that you can catch in your subscription.

  1. removeFooFromList(id: number) {
  2. this.demoService.deleteFoo(id).subscribe(
  3. foo => {
  4. // Do something with foo.
  5. },
  6. error => {
  7. // Do something with error.
  8. }
  9. )
  10. }

How to Get a Specific API Endpoint From Application Config

Another nice config option that request method receives is apiName (available as of v2.4), which can be used to get a specific module endpoint from application configuration.

  1. putFoo(body: Foo, id: string) {
  2. const request: Rest.Request<Foo> = {
  3. method: 'PUT',
  4. url: '/' + id,
  5. body
  6. };
  7. return this.rest.request<Foo, void>(request, {apiName: 'foo'});
  8. }

putFoo above will request https://localhost:44305/api/some/path/to/foo/{id} as long as the environment variables are as follows:

  1. // environment.ts
  2. export const environment = {
  3. apis: {
  4. default: {
  5. url: 'https://localhost:44305',
  6. },
  7. foo: {
  8. url: 'https://localhost:44305/api/some/path/to/foo',
  9. },
  10. },
  11. /* rest of the environment variables here */
  12. }

How to Observe Response Object or HTTP Events Instead of Body

RestService assumes you are generally interested in the body of a response and, by default, sets observe property as 'body'. However, there may be times you are rather interested in something else, such as a custom proprietary header. For that, the request method receives observe property in its config object.

  1. getSomeCustomHeaderValue() {
  2. const request: Rest.Request<null> = {
  3. method: 'GET',
  4. url: '/api/some/path/that/sends/some-custom-header',
  5. };
  6. return this.rest.request<null, HttpResponse<any>>(
  7. request,
  8. {observe: Rest.Observe.Response},
  9. ).pipe(
  10. map(response => response.headers.get('Some-Custom-Header'))
  11. );
  12. }

You may find Rest.Observe enum here.

What’s Next?