简体   繁体   中英

How to take data from local storage and to show in table in angular?

I have made a login form which take username and password and store it into local storage and when clicked on login it shows welcome {username} on different page.But it only stores one username in localstorage. when we enter another username the previous get overwrite. i want to display all the usernames.

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

}
<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, Input } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
user;

  constructor(private router: Router) { }

  onLogout() {
    this.router.navigate(['']);
    // localStorage.clear();
    alert('you will be loged out');
  }

  ngOnInit() {
    this.user = localStorage.getItem('username');
    }

}


<p>
  Welcome {{user}}
</p>

<button (click)="onLogout()">Logout</button>

I need to store each and every username entered to be stored in localstorage and to retrieve that usernames on home-page from that localstorage.

First of all you need to understand how localStorage works. Local storage works as key value pair. You can achieve that by saving different username as different keys and then to get the values you need to use all the keys. Please read this for more information : How to Use Local Storage with JavaScript

By the way it is not recommended to save passwords in the local storage.

you can do something like this, to store them as array

to store them:

const newUsers = [...JSON.parse(localStorage.getItem('username')),this.model.username];
    localStorage.setItem('username', JSON.stringify(newUsers));

and then to use:

const users = JSON.parse(localStorage.getItem('username'));

LocalStorage acts like a key-value map to save variables.

When you do

 localStorage.setItem ('username', this.model.username);

client saves in browser the key "username" with the value this.model.username. Another client/browser will save his own value, but key 'username' refers to only one "storage unit".

Behaviour you are trying to implement has not sense in functional terms since you are using it to store as if it was a relational database.

You can understand local storage like cookies storage they act the same.

If you still want to use it as storage for your purpose, you can make a counter and implement a function to do:

localStorage.setItem ('username' + counter, this.model.username);

Then read those by iterating and store in an array, for example.

But I insist it is not a good idea because if the purpose is to try you can store them in an array simply

There is a fantastic library for this called ngx-webstorage you should try it out.

Store

import {Component} from '@angular/core';
import {LocalStorageService} from 'ngx-webstorage';



@Component({
    selector: 'foo',
    template: `
        <section><input type="text" [(ngModel)]="attribute"/></section>
        <section><button (click)="saveValue()">Save</button></section>
    `,
})
export class FooComponent {

    attribute;

    constructor(private storage:LocalStorageService) {}

    saveValue() {
      this.storage.store('boundValue', this.attribute);
    }

}

Retrieve

import {Component} from '@angular/core';
import {LocalStorageService} from 'ngx-webstorage';

@Component({
    selector: 'foo',
    template: `
        <section>{{attribute}}</section>
        <section><button (click)="retrieveValue()">Retrieve</button></section>
    `,
})
export class FooComponent {

    attribute;

    constructor(private storage:LocalStorageService) {}

    retrieveValue() {
      this.attribute = this.storage.retrieve('boundValue');
    }

}

to answer your question.

  1. LocalStorage is composed of name/value pair. So by doing this, you're overriding the value of previous username (let say you're testing on the same browser window)
localStorage.setItem ('username', this.model.username);
  1. "I need to store each and every username entered to be stored in localstorage and to retrieve that usernames on home-page from that localstorage."

In reality, each user will login with their own system & so have different instance of localStorage. They will see their own username after login in. For testing purpose, you can open multiple browser (Chrome, Firefox, etc.), login & inspect the value of the same key.

It's more of a common practice to extract username from your JWT token after a success response from your app authentication API (assume that you have integrated with backend)

  1. "...when we enter another username the previous get overwrite. i want to display all the usernames."

I'm not quit sure about the usecase of this.

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