In order to communicate with web services in Angular, it is best to use the HttpClient. The HttpClient has a number of benefits such as testability, strongly typed request and response objects, Observable APIs, and error handling.

The first step to using the HttpClient is to modify the imports section of your module to include the HttpClientModule. Then, by using dependency injection, inject the HttpClient into the constructor of your service. Next, provide a web service URI to the get function.

this.http.get<IUser>(webServiceUri);

Make sure to provide an object type in the get function’s generic parameter.

The http.get function returns an Observable which let’s you subscribe to the web request and be notified when the result has returned.

http.get<IUser>(uri).subscribe(data => this.myProperty = data)

You can use Operators to perform operations on the result and handle errors. By using the pipe function, you can chain together multiple Operators. For example; to handle errors use the catchError operator like this:

http.get<IUser>(uri).pipe(catchError(this.handleErrors))

handleErrors(error: HttpErrorResponse){
return throwError(error.message);
}

To read more about the HttpClient and better understand Observables and Operators, please read the Angular documentation: https://angular.io/guide/http

Brian Lagunas

View all posts

Follow Me

Follow me on Twitter, subscribe to my YouTube channel, and watch me stream live on Twitch.