Skip to content

Tech Leads Programming Class Week 4

Posted in Javascript, and Personal

In this week’s class, it is about time we prepare our client-side application to talk to our server. Our client – the application in the browser – will make requests to the server, and display responses from the server.

We will be using REST for our means of communication with the server from the client.

Creating Services

Think of a service as a piece of our application code that we can use at many areas of our application. Instead of writing the same piece of code to do something (such as sending user info to login) every now and then, we could just create just one Authentication Service, and then we could import this service in as many files as we want.

This ensures by simply changing one file, we can effect change at all the areas we have imported that service. file. We’ll see it in use soon.

Creating services in Angular is straightforward, with the Angular CLI (Command Line Interface)

We’ll create 3 services:

  • Authentication Service (for all our user authentication needs i.e, login, logout)
  • Account Service (For user to manage their submitted serial numbers etc)
  • Code Service (For user to send, update or delete submitted serial numbers)

To create the services, we use the Angular CLI commands:

The g stands for ‘generate’, service is the type of file we want generated,  and the auth is the name we want give to our service.

The --spec false is simply saying we don’t want any testing specifications. You don’t have to worry about that. You can enter the command without the --spec false and see what happens

Now, create a folder, called providers and put the generated service files into it. It should look like this:

Therefore, we now have all our service files in one folder for easy referencing as we move on.

The complete contents of our auth.service.tsfile is available in this link. I’ll only be running commentary on it here. It is a long file, and adding the contents here won’t be necessary.

auth.service.ts

On line 11, we have the getHeaders() method, which returns a custom header object for us. If a token is available in the localstorage, as in, if the user is logged in, the value of the token is attached to our Authorization field.

Starting on line 21, as our AuthenticationService class is instantiated, we make the Httpclass available for use. It is the Http we’ll be using to send and receive requests from the server.

The /** ... */ part is simply for JSDocs. Code documentation. Not mandatory, but is useful. Whenever you’re trying to use the register() function of the AuthenticationService, depending on your code editor, it might use the information in the /** ... */ to guide you.

Our register() function takes 5 parameters.

We make a params object containing the parameters from the register()and pass it to the http.post() method, which sends the data to the server and waits for a response.

You see we doing return. Simply saying, the register() function should return an RxJS Observable, which we would then subscribe to. Therefore, until we subscribe to the register() function, the request to the server won’t happen.

The http.postmethod allows a few parameters on itself. The first is the link where we want to post to. In the above instance, it’ll become http://localhost:3021/auth/register. The AppSettings.API_ENDPOINT is a constant, coming from the contants.tsfile within our src/app/providers/folder.

We, therefore, stringify, converting our params object into a JSON string for sending.

Then, we attach our custom headers, which is calling the getHeaders()function, which simply returns an Http Header object containing a Content-Type and Authorization fields.

Whatever response we get from the request, we return everything, in this case, namely the resobject.

The other function follows a similar pattern.

Lemme just touch on briefly the login() function

localStorage provides an interface for us to quickly store and retrieve stuff from the storage in a browser. Every browser has an allocated storage space for websites. We can take advantage of that via the localStorage API.

So when a login is successful, a few details is sent back, such as the token and user. We store this in the browser.

It is this token that we retrieve and attach to the header object when we want to make requests. If the token isn’t available, the Authorization field would just be empty.

localStorage.setItem('name_of_item', 'actual item to store').

There’s a little if { } block of code. We want the setting stuff into the local storage to happen ONLY when login was successful. The check for a login success is done by looking at the statefield of the returned response object. If state is true, voila. Otherwise, just send the res object to the login component, and it’ll handle the rest.

Don’t worry, all shall be seen in action pretty soon.

Read through the code, and see if it all makes sense. I mean check the other parts of the code of the auth.service.ts. Fortunately there is a bit of documentation and explanation of what each function does. Just be familiar with the code, and let’s move on.

Login Logic

The code below goes into the src/app/login-register/login-register.component.ts file:

I know what you might be thinking. That seems like a lot of code. In fact, it kinda, because we’re trying to give a useful experience to the user trying to log in or sign up/register.

Because of the above import, we need to do a few changes to our application.

ngx-toastris a nice Angular package which allows us to show toasts (notifications) in our application.

Read what toasts are meant for here: https://material.io/guidelines/components/snackbars-toasts.html

Here are the changes you need to do

First, install ngx-toastr. In the command line of your project root, enter npm install --save ngx-toastr @angular/animations

Add ngx-toastr CSS file to your Angular CLI project. Find the .angular-cli.json in the Menpha/project folder.

Update the styles: [ ] part to look like this:

Next, import both the ngx-toastr and @angular/animations in your AppModule

Your AppModule.ts file should end up looking like this:

If you have been running ng serve all this time, you’ll notice there are no more errors in the console.

There’s gonna be some more errors, so hold on tight. We’ll fix them all though. Don’t worry.

Here’s our login-register.component.html file. Update yours to have the contents below.

Now, errors, errors everywhere

Errors Everywhere

Let’s fix them one by one.

First, add this import to your app.module.ts file:

import { FormsModule } from '@angular/forms';

Then add the FormsModule to your importsproperty. You should end up with this:

There is an error about recaptcha. We use recaptcha to do the ‘I’m not a robot’ verification thing.

Install the nifty angular package for that via npm install --save ng-recaptcha

Import, then, in the AppModule like this: import { RecaptchaModule } from 'ng-recaptcha';

And then add to the imports [...] property like so:

All the errors should be gone by now.

Take a deep breath, and congratulations.

So let’s move on to…

Was just kidding. We’re done for today.

What we’ve been able to achieve so far in this lesson are all available on Github at this link:

https://github.com/seanmavley/techleadsclass/tree/Authentication

Conclusion

That’s all we need to log in and register users. Pretty straightforward. I won’t say it is easy, but it CAN be easy. Take your time, and go through the lines. There’s NO magic happening anywhere. And fortunately, the code is like English, that by simply reading, you could understand what is being said or done.

Will see you in the next one, as we setup our server for handling the login from our client. It’ll be fun.