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:
export interface User {
id: number;
username: string;
}Then add another file called
AuthUser.ts
import { User } from './User';
export interface AuthUser {
tokenString: string;
user: User;
}Import HttpClient
In your
app.module.tsadd an import for theHttpClientModuleafter theBrowserModule:
import { HttpClientModule } from '@angular/common/http';
// ...
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],Angular AuthService
In the project root of your
SPAproject run this command to generate a services folder and anauth.service.ts:
In your new
auth.service.tsfile - import theHttpClient,HttpHeaders, ourAuthUser, and therxjs mapoperatorAlso, inject the HttpClient into the constructor. See the code below:
Add a property called
baseUrlset to the auth endpoint and a property calleduserTokenof type any:
Next, let's go ahead and register our service in
app.module.tsin 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.tsfile, inject theAuthServiceinto 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