[EN] Creating component and service in Angular2

Two posts ago I wrote about Angular2 application and I showed how to add new component and service. This time I want to show you how to implement a service in Angular2 and call webApi from it.

I decided to create login service in angular app which calls SignIn method from webApi (request via http post method).

Ok, let’s start. I have login.component and login.service in my angular app. First we need to make sure if login service is imported in login.module.ts and if it is added to providers list.

Next let’s implement the service.

First we need to import few things. You can ignore app/constants as you can see in my code, it’s just simple typescript class that contains constants. In the constructor we need to create http variable which will be used later.
SignIn function takes two parameters: username and password and returns boolean value. Then we have to construct http request that will be send to webApi. It’s very important to add headers that informs request contains json content, because webApi only accepts jsons. After http.post method there’s another method – map, which transforms the result to whatever we want.

Next is time to implement some code in login.component class. Let’s start from imports, don’t forget to import our service.

I have few variables in my login component, like username, password and 3 others that indicate an error. You can skip it, it’s not needed to achieve our goal from this post. I use it only to check if username and password are valid and show an error message in case they are not valid.

Let’s focus on onLogin() method. After few validations signIn method from login service is called with username and password which are passed as arguments. Subscribe method allows to define operation that we want to execute when result will come. I want to save username in localstorage and navigate to different component – welcome component.

What about login.component.html? It depends from you how you want to design it. There are a lot of samples in bootstrap 😉 Here is mine.

1

Basically you need to create a form.

and add ngSubmit directive that enables binding expressions to onsubmit events. We have onLogin method in login component that will handle it. We need also to bind input controls to our model

It will bind value from this control to _username variable in component class. I have also method binds to keyup event, but it’s only for validating input data. onKeyUp method in the component is responsible for it.

It looks we have all. Our service in Angular2 is ready. Now it’s time to start app and try to call webApi, but we will take a look at it in the next post.

One comment

  1. Pingback: dotnetomaniak.pl

Comments are closed.