Kun-Yao Lin
155 words
1 minutes
[Angular] #3 Login Component

Layout#

login

Steps#

  1. add login component by ng generate component login
  2. modify login.component.ts
     import { Component } from '@angular/core';
     import { FormsModule } from '@angular/forms';
     import { UserService } from './UserService';
    
     @Component({
         selector: 'app-login',
         standalone: true,
         imports: [FormsModule],
         templateUrl: './login.component.html',
         styleUrls: ['./login.component.css'],
         })
         export class LoginComponent {
         constructor(private userService: UserService) { }
    
         login(email: string, password: string): void {
             this.userService.login(email, password).subscribe(
             response => {
                 console.log('login success', response);
             },
             error => {
                 console.error('login fail', error);
             }
             );
         }
     }
    
  3. modify login.component.html
    <div class="login-container">
        <form (ngSubmit)="login(email.value, password.value)">
            <div class="form-group">
            <label for="email">Email:</label>
            <input type="text" #email placeholder="Email">
            </div>
            <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" #password placeholder="Password">
            </div>
            <button type="submit">Login</button>
        </form>
    </div>
    
  4. add UserService.ts
     import { Injectable } from '@angular/core';
     import { HttpClient } from '@angular/common/http';
     import { Observable } from 'rxjs';
    
     @Injectable({
         providedIn: 'root'
         })
         export class UserService {
    
         private apiUrl = 'http://localhost:8080/demo'; //
    
         constructor(private http: HttpClient) { }
    
         login(email: string, password: string): Observable<any> {
             const url = `${this.apiUrl}/login`;
             return this.http.post(url, { email, password });
         }
     }