3.2: Client-side Login
Add User and AuthUser models
In your app folder, create a new folder called
models.
Add a new file called
User.ts with the following code:
Then add another file called
AuthUser.ts
Import HttpClient
In your
app.module.ts
add an import for theHttpClientModule
after theBrowserModule
:
Angular AuthService
In the project root of your
SPA
project run this command to generate a services folder and anauth.service.ts:
In your new
auth.service.ts
file - import theHttpClient
,HttpHeaders
, ourAuthUser
, and therxjs map
operatorAlso, inject the HttpClient into the constructor. See the code below:
Add a property called
baseUrl
set to the auth endpoint and a property calleduserToken
of type any:
Next, let's go ahead and register our service in
app.module.ts
in the providers array:
Login Method
Now, we're ready to write our
login()
method inauth.service.ts
: <!-- ```typescript login(model: any) { return this._http.post(this.baseUrl + 'login', model, { headers: new HttpHeaders() .set('Content-Type', 'application/json') }) .map(user => { if (user) { localStorage.setItem('token', user.tokenString); this.userToken = user.tokenString; } }); }Using the AuthService in our Nav Component
In the
nav.component.ts
file, inject theAuthService
into the constructor. We'll make it public here because we'll use it in the template.Modify the
login()
method to use ourAuthService
.We'll still log our result to the console (and also an error message) for testing purposes.
Testing the Login Method
We need to start up our .API
project and our SPA
project. Preferences may vary - you can decide between the built-in terminal in VS Code or using a separate terminal.
Navigate to your two projects and start up the servers
With your browser's console open, enter an actual username and password that you know is saved to your database.
You should get the logged in successfully
message:
Now, navigate to the network tab in your developer tools.
You should see the 200 Ok
response.
If you're using Google Chrome - click on the Application
tab and then Local Storage
and verify that our token is being stored in the browser's storage:
Chrome:
If you're using Firefox, click the Storage
tab and then Local Storage
:
Firefox:
Nice job! Logging in works!
Last updated