Create an Angular Service to Retrieve Data from an API

Bram Borggreve
InstructorBram Borggreve
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

In this lesson we will create the ProductsService that is responsible for the interaction with our API.

We will inject the HttpClient that we get from @angular/common/http. To make this working we need to import HttpClientModule in our AppModule.

We define a getProducts and getProduct method so we can get a list of products and an single product which we will use in respectively the ProductList and ProductDetail components.

In both components we will use the ngOnInit lifecycle hook to invoke the methods on the service, and retrieve the data by subscribing to it.

Link to product api used in lessons

Instructor: [00:00] We run ng g s product/services/product to create our service. We open up product service and inject dependency called private HTTP of type HTTPClients. Below our imports we add a const [inaudible] base URL and set the value to a template literal. We'll take the value API URL from the environment we just created and append/products.

[00:24] We now create a public method getProducts that does not take any parameters and returns an observable of type products array. In this method, we return this.http.get and pass in the base URL. We [inaudible] the get method, using a generic that we expect to retrieve an array of products.

[00:43] Then, we add a public method getProducts that takes ID as a string and returns an observable of type products. We make it return this.http.get and pass in the base URL with the / and the ID appended to it.

[01:00] In order to use those methods, we open product list components, and in our constructor, we inject PrivateService ProductService. In our ng onInit method, we call into this.service.getProducts, so try to that methods and assign the results to this.products.

[01:16] When we reload our app, we see that we have an error message, "No provider for HTTPClients." In order to fix this, we open our app module and add HTTPClient module to our imports array, and make sure we import it from angular/common/http.

[01:31] When we reload, we finally see the list of products being displayed and our error is gone. Let's update product [inaudible] components, inject PrivateService ProductService, and ng onInit this.servers to getProducts. We pass in the parameter we get from the router.

[01:48] We subscribe to it and assign the results to this.product. We can now navigate through our app and see that products get loaded.