Angular 5 HTTP Form Inputs & RxJS

Angular 5 Form Inputs

Whatever framework you are using, forms are a key component of any website or web application.  They provide us with one of the most important aspects of user interaction. We need to give the user a clear understanding of what information we require, while also validating his/her data in the process.

If we want to provide a real-time interface for the user that reacts to his/her inputs and selections, we can use RxJS Observables and Angular form controls.

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

.

The application takes user input, sends off a HTTP request while the user is typing and retrieves a new dataset based on their current search term in real-time.

The user can also change the beer category through a drop down selector in the same way to get a similar user interface update.

The full repository for Beer Name Finder is available here.

I think this is one of the coolest things about modern UI manipulation when combined with modern frontend frameworks. And surprisingly, it is not overly difficult to get running once it is broken down into different segments. I will detail how to go about that in this post.

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

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

So, let’s begin.

Populate an Angular Input

Let’s say we want to populate a select dropdown field from a HTTP call. I used this process for my Beer Application so I’ll be using that as an example.

To start, I retrieved a list of beer categories from the BreweryDB API and applied them to a select dropdown field.

In our search.component.ts I declared the main variable types used:

The FormControl is the most notable declaration here:

It tracks the value and validation status of an individual form control e.g input field.

It is one of the three fundamental building blocks of Angular forms, along with FormGroup and FormArray.

I declared an array of type Beer from an imported TypeScript definition:

This maps our desired beer properties from our HTTP request to a beer object.

My imported type definition for Beer looked like this:

I then initialised my data service (beer.service) in the constructor:

I used a method in _beerService to retrieve the beer categories to populate the select dropdown field.

In my lifecycle hook ngOnInit I then invoke two custom functions:

The first initialization of the dropdown contains this functionality:

I got an initial dataset of beers from our getBeers() function I have covered this function extensively in another post here:

After this, I invoked the getCategories() method from the beerservice file which contains the following functionality:

This is yet another HTTP request similar to all others in the service.

this._baseUrl refers to the BreweryDB API endpoint:

The only unusual thing in the getCategories method is the Array.from(new Set(this.categories))

This could have been done a number of ways to get a new array object from an iterable but I used the Array.from() method here but this is just personal preference.

So now my categories object will now contain data from our request that look something like this:

If we now examine our markup for the form we can see this:

Just concentrating on the select field for the moment:

We can see that the *ngFor directive has iterated through our retrieved categories array. At this point, I navigated and selected a category option.

This next section is possibly the most interesting thing about creating a reactive input in Angular 5. It uses RxJS methods to track data from an input field and allows you to manipulate that data from that input field as an Observable.

We now are going to look at the method listenForInput():

So starting with:

This term value is a reference to our FormControl declared earlier in the file:

The debounce time:

Waits for a new change in the input field from the user every 400 milliseconds. If a change occurs before 400 milliseconds from the previous change it discards those values.

The distinct method:

Ensures that there is a new value in the input field before declaring that theres been a change.

Once this criteria is met, we are finally able to subscribe to the Observable:

From here I have invoked:

This is just another http call to retrieve a list of beers using the parameters term and this.currentCategory which will filter the response to the desired dataset.

I’ll show you this searchTerm method as well:

This seems quite complicated but its actually not doing much more different than any other of our HTTP calls in the service.

We are using the term from our input field in the api request:

We are making sure that the category property exists in the our respoinse:

But most importantly, we are assigning this new information to our beer observable source by using .next().

This beer observable is being subscribed to elsewhere in the application so the UI will automatically get refreshed which is very handy.

And when we have selected a new value currentCat(selectedCategory.value) will be called:

This is just one example of using RxJS and Observables to track  a users interaction with a form element and have the UI refresh accordingly.

On a side note, Observables in general should be used when there is more than one stream of data. This is when they are most effective. But its fun to demonstrate their power in an application such as this.

The full repository for Beer Name Finder is available here.

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.