我正在嘗試使用 Angular 制作一個登錄頁面。我有一個處理此功能的 Angular 組件(html、css 和 ts 文件)。在 HTML 中,有兩個字段和兩個按鈕。用戶名、密碼、登錄和注冊。如果您輸入不熟悉的用戶名和密碼并單擊注冊,我希望 TS 組件將此用戶(帶密碼)添加到有效組合列表中。如果我用我的硬編碼用戶(邁克爾)登錄,它工作正常。如果我注冊一個用戶并立即登錄,它也可以。但是當我注冊一個用戶并刷新頁面時,新注冊的用戶從列表(用戶)中消失了。HTML:<div *ngIf="loggedin === false"> <label for="username">Name</label> <input id=username [(ngModel)]="username" type="text"> <label for="password">Password</label> <input id=password [(ngModel)]="password" type="password"> <button type="submit" (click)="login(username,password)">Login</button> <div class="snackbar"> <button (click)="register(username,password)">Register</button> </div></div>TS:import {Component, OnInit, ViewEncapsulation} from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar';export class User { username:string; password:string; constructor(username, password){ this.username = username; this.password = password; }}@Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], encapsulation: ViewEncapsulation.None})export class LoginComponent implements OnInit { static users: Array<User> = [new User('Michael', 'admin')]; username:string; password:string; loggedin:boolean; constructor( private _snackBar: MatSnackBar ) { } ngOnInit(): void { this.loggedin = false; } login(username, password){ let currentUser = new User(username, password); LoginComponent.users.forEach((element) => { if (element.username == currentUser.username){ if (element.password == currentUser.password){ this.loggedin = true; } else { alert('Incorrect password'); } } else { alert('Unknown user'); } }); } logout(){ this.loggedin = false; window.location.reload(); }主要問題:刷新時如何將用戶數組保存在內存中?鑒于我不想添加后端(此時正在開發)
Angular 應用程序 - 靜態列表在刷新時清空
絕地無雙
2022-12-18 16:08:35