我有一个名为model
的对象,我希望它存储在localstorage中。
model.username和model.password是我表单的两个字段。我想将model.username存储在本地存储中。我需要添加要添加到本地存储中的每个用户名。但是就我而言,每次我尝试输入新用户名时,以前的用户名都会被覆盖在本地存储中,即,任何时候都只能在ls中存储一个用户名。
以下是登录模板
<form (ngSubmit)="f.valid && onSubmit(f) " #f="ngForm" novalidate>
<div>
<label for="username">Username</label>
<input type="text" name="username" [(ngModel)]="model.username" #username="ngModel" required appForbiddenName="jimit" />
<div *ngIf="f.submitted && !username.valid" >Username is required</div>
<div *ngIf="username.errors.forbiddenName">
Username has already taken.
</div>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" [(ngModel)]="model.password" #password="ngModel" required />
<div *ngIf="f.submitted && !password.valid">Password is required</div>
</div>
<div>
<button type="submit" >Login</button></div>
<div>
<button type="reset">Clear</button>
</div>
</form>
<button (click)="onRegister()">Register</button>
以下是登录组件
import { Component, OnInit } from '@angular/core';
import { FormBuilder, NgForm } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private router: Router) {
}
model: any = {};
onSubmit(form: NgForm) {
console.log(form.value.username);
console.log(this.model.username);
localStorage.setItem ('username', this.model.username);
this.router.navigate(['/home']);
}
onRegister() {
this.router.navigate(['/register']);
window.alert('please wait while we process your request');
}
ngOnInit() {
}
答案 0 :(得分:1)
忽略将多个用户名存储在localStorage
中的奇怪想法,您可以通过插入数组或对象来实现。因为localStorage的键是唯一的:
const usernames = JSON.parse(localStorage.getItem('usernames') || '[]');
if (!usernames.includes(this.model.username)) {
usernames.push(this.model.username);
localStorage.setItem('usernames', JSON.stringify(usernames));
}
但是,如果您这样做是为了在导航后稍后获取数据,我建议您全面了解如何使用服务/存储而不是localStorage。
答案 1 :(得分:-1)
本地存储基于键存储值,并且一次仅保存一个值,而不保存数组。