ตัวอย่างโค้ด login ใน angular

เราไปดูตัวอย่างโค้ดหน้า login โดยใช้ angular กันครับ

เริ่มจากหน้า template ก่อนเลย ตามโค้ดด้านล่าง

<form (ngSubmit)="login()">
  <label for="email">Email:</label>
  <input type="email" id="email" [(ngModel)]="email" name="email" required>

  <label for="password">Password:</label>
  <input type="password" id="password" [(ngModel)]="password" name="password" required>

  <button type="submit">Login</button>
</form>

จากนั้นใน component เราจะเพิ่ม FormsModule เข้ามาใช้ ตามตัวอย่างโค้ดด้านล่าง

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  email: string;
  password: string;

  constructor(private http: HttpClient) { }

  login() {
    const user = {
      email: this.email,
      password: this.password
    };

    this.http.post('/api/login', user)
      .subscribe((response) => {
        // Handle successful login
        console.log(response);
      }, (error) => {
        // Handle login error
        console.log(error);
      });
  }
}

เพียงแค่นี้เราก็ได้แล้ว ต่อไปเราก็ต้อง ออกแบบการเก็บ token หรือ handle การ login ต่าง ๆ

ตัวอย่างนี้เป็นเพียงตัวอย่างแบบง่าย ๆ ต้องลองนำไปปรับใช้กับ application เอาเอง



Copyright © 2023 Devcode Code Example - Powered by www.doesystem.com