简体   繁体   中英

How can i store object in local storage in angular?

i have an object named model i want it to store in localstorage .

model.username and model.password are two fields of my form. i want to store model.username in local storage. i need to add every username to be added in local storage. But in my case every time i tried entering new username the previous username get overwritten in local storage ie only one username is only stored in ls anytime.

Following is the login template

<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>

Following is the login component

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() {
  }

Ignoring the strange idea of storing multiple usernames in localStorage , you can do this by inserting an array or object. Because the keys of localStorage are unique:

const usernames = JSON.parse(localStorage.getItem('usernames') || '[]');

if (!usernames.includes(this.model.username)) {
  usernames.push(this.model.username);
  localStorage.setItem('usernames', JSON.stringify(usernames));
}

If however you are doing this to get the data later after navigating, I suggest you have a thorough read about using services/store instead of localStorage.

本地存储基于键存储值,并且一次仅保存一个值,而不保存数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM