Angular 5 HTTP using Observables – Part 2

WRITTEN BY GARETH DUNNE @JSDIARIES

Angular 4 HTTP & Observables

In this part of the tutorial we will be focusing on our API calls and how they interact with the BreweryDB API.

Again, if your looking to expand your Angular and Typescript knowledge I highly recommend this Angular & TypeScript book by Yakov Fain.

You can see the final version of what my beer app is here.

Angular Proxy & CORS

First up, in order to get data from the BreweryDB API we want to enable CORS (Cross Origin Resource Sharing) in our browser.

To accomplish this we have two choices:

The easiest option here is to install a CORS Chrome extension here.

This will enable you to perform cross origin shares in Chrome without having to setup a local proxy. This is handy for testing an application locally but would obviously fall short if pushed to a production environment or hosted externally.

The second option, which is something I would encourage you to do is to setup a local proxy. This will allow you to easily enable cross origin resource sharing for all your browsers and doesn’t take long to create.

To do this lets first create a proxy.config.json file in the root of our project directory.

Proxy file location
Proxy file location

This is our proxy API json object. It contains properties that allows our calls to send and receive data to the Brewery API.

However, it won’t work without running the proxy file alongside our application. So we will need to execute this command to start it alongside our application.

Mapping Data to TypeScript Interface

Next, we need to create a beer view model. This will basically act as an interface for our retrieved data. Properties such as name, description and rating will feature here.

In your app folder create a file called beer.ts and put in the following.

This is only a basic version of the actual beer data returned to us by the BreweryDB API.

The data response contains a lot more properties than this but you can always customize the interface to match the data you desire to use in your UI.

We can now import our Beer type definition to any of our components to reference the data retrieved from BreweryDB.

This is a pretty common thing to do when using TypeScript and making HTTP requests for data.

This is also a benefit of using some of the object oriented aspects of TypeScript.

It allows us to code defensively and ensure that we have the exact data properties that we need for the project. Otherwise it will throw a Type error and you can adjust the type definition accordingly.

Get the Data using Angular HTTP Object

We now want to implement a method that retrieves all beers from our Beers API.

Open up beer.service.ts and change it to the following.

So we now have a getBeers() method and a handleError method for our API calls.

In the first condition we check if the this.result variable already has a value:

This is an important step because our service shares permanent data throughout our application so if the application has already been loaded then there is no point in making the getBeers() API call again as the data is already cached in the our browser/service to be used.

We then take the _http variable of type HTTP that was created in our constructor:

And then invoke the get method using our beer API url details as the parameters for it.

The next line:

Takes the response from the Beer API server and maps it into a JSON array for us.

This will allow the data to be reactive. We will come back to this.

This line has a similar function. It allows the Observable returned by the HTTP get request to keep its connection open, this will allow the data source to be reactive.

We also will catch any errors here:

This line will catch any error from our request and run the this.handleError function.

All you really need to know about this function is that it will filter down through the error message to the point where it will usually be the most informative. Usually, a detailed HTTP code error or something associated with that code.

Observables Ready for the UI

If you noticed some of the variables declared above the constructor, at the top you should see:

These are both core Rxjs features that will allow our data to be reactive. We will come back to these but for now just think of them as reactive variables that we will using later on in our home.component.ts .

Retrieving the Angular Data

This is the basic version of our service set up with the functionality to retrieve an initial list of beers. It gives a good overview of how our service will share data. However, this on its own will not do anything without using it into one of your UI components.

We will be doing this in part 3, for now think of this service as a piece of functionality that will share data throughout the application, the data will be made reactive by using Rxjs Subjects and Observables which are declared at the top of the file.

Angular 5 HTTP using Observables – Part 1

WRITTEN BY GARETH DUNNE @JSDIARIES

Angular 5 Data Binding

One of the more advanced aspects of frontend development to know as an experienced UI developer is the creation of reactive data sources.

No matter what kind of data you want to show your user, in order to take advantage of web applications you should really have your data be dynamic and reactive.

In comparison to libraries like React.js, Angular 4 enables you to create data that is shareable to all of your UI components via a service .

In Angular,  we can use Observables and Subjects to make this data reactive and as a result refresh our UI. This is achieved by using an external reactive JavaScript library called Rxjs.

I won’t be going into too much detail on what goes on behind the scenes of the Rxjs library but just know that it is an important aspect of using data in the Angular project.  In this tutorial I will demonstrate how to use it as dynamic data retrieving tool.

And while Rxjs is also available to be used with React, in my personal opinion it is much easier and it better fits the architecture to be used in combination with Angular 5.

Redux is more commonly used in combination with React for the data flow and state management of a project but the details of that can be found in another post here.

In this tutorial, I want to demonstrate how you can make your own reactive data source using BreweryDB’s APIs. I also want to show how modern frontend frameworks like Angular allow us to create seamless user interfaces that respond to the changing of data.

In this part, we will just start with setting up the project.

On a side note, if your looking to expand your Angular and Typescript knowledge I highly recommend this Angular & TypeScript book by Yakov Fain.

This tutorial series is based on my application Beer Name Finder which you can view here:

.

If you enjoy this dashboard, please consider giving it an upvote on Product Hunt here.

I took the designs and styles of this application from Coursetro’s MEAN stack tutorial and was able to implement a service for interactions with the data and the Brewery API.

Angular Observables

As this tutorial will be broken down into a few posts, you can see the source code in the GIT here.

Brewery API

In order to retrieve data from a source via HTTP we will use the Brewery API. This will at least keep our data source interesting and offer plenty of different data options to be displayed.

Navigate to the developer API section here.

Brwery API Menu
Brewery Applications

After signing up for a developer account, create a new application with whatever details you like.

Register New Application
Register New Application

The documentation is quite verbose and you can find a wide variety of different ways to query the api for specific beers.

You can also test the results of any api calls via the api explorer. This is useful for when you are testing different query parameters to retrieve specific datasets of beer information

API Explorer
API Explorer

For now, we just need the api key generated by your app. This will be needed in order to make a http request to the Brewery API server so store this somewhere to reference later on.

Angular 5 Install & Setup

In order to progress from here we need to have Node.js and the Angular CLI installed.

I’d recommend to getting started by watching this video by Gary Simon from Coursetro who details the installation steps.

Once set up from the instructions of that video, we need to scaffold the structure our Angular application. This is very easily done through the Angular CLI.

Open up the terminal or command window and in the current directory we want to generate the project with the styling scss flag.

We have now generated a Angular project with a solid SASS styling structure. This step is of course optional depending on your CSS preprocessor preferences.

If you want to style the project with normal CSS that is fine too.

Angular 5 HTTP Service & Home Component

Next, lets generate our home component. This is a component that will contain all of our UI for displaying all the beer data requested from the BreweryDB API.

From here, we want to generate our service that will hold all the logic for retrieving data that can be shared with any our components.

This is a service that contains all our methods that we will use to request data from BreweryDB’s APIs. When you open up this service you will see that the Angular CLI has automatically injected a HTTP object into the constructor for us.

Lets modify this service so it now looks like this.

The HTTP object in the constructor will be used to make the HTTP requests to the BreweryDB APIs. Meanwhile, we have added all the necessary imports in the top of the file that we will need later on for this service.

Angular 5 Setup Complete

This is our basic structure set up. In part 2 we will add our API calls to our beer service.