This process is similar to the register setup except the user would already have registered an account with your database by this point. The only difference is that we will collect only the email and password from the user and hit a different api route when we try to login a user to our application.
This following code will collect user information by capturing it through html input tags in the login.component.html. We will store the inputs in a form object inside the login.component.ts using two way data binding. The form object will hold the email and passwordvalues collected via the login.component.html.
Once the data collected through the html file is bound to the typescript file, a user will click the login button. Once pressed, the button's (click) event will fire, which will invoke the login.component.ts's login function.
The login.component.ts's login function will then invoke the userService's loginUser function which will make a HTTP POST to the loopback server's /appUser/login api route, passing in the user credentials, aka the 'form' object passed by the login.component.ts.
Inside of the login.component.ts's login function we will subscribe to the result of the invocation of the userService's loginUser function. The subscribe function will accept a callback function as an argument. This callback function will run once the data has been sent back from loopback's server to the client. This callback function will accept a parameter, typically this parameter is called res, symbolizing the response from the HTTP request. In the callback function's scope we will store some of the response's attributes, such as the user's id and a token, to the client's local storage.
We will then use this token value to hit other api routes in our loopback server to communicate database. This token is a security feature to ensure accessibility only to certain people. This will be discussed in more depth later in the course.
Make Sure We Have Done The Following Inside the user.service.ts:
Imported the HttpClient in the user.service.ts
Initialize HttpClient inside the user.service.ts constructor
Create the following Attributes in the UserService Class:
baseUrl: string = "http://localhost:3000/api";
appUserUrl: string = "appUsers/"
loginUrl: string = "appUsers/login"
Create A loginUser Function In The User.service.ts File
This function will accept a userCredentialsparameter.
This function will make a post request to the loopback server's localhost:3000/api/appUsers/login/ route, which will then submit the userCredential data to the mongo database.
Alter the login function inside login.component.ts
This function login will invoke the userService's loginUser function, passing in the user credentials, aka the login.component.ts's form object.
When we subscribe to the observable we will do the following
populate session storage with the responses token attribute
populate session storage with the responses userId attribute