Angular2 How to display localStorage value inside

2019-07-15 05:08发布

问题:

I store 2 keys in localStorage and I'd like to display one of them in my template. I can't access these values. I even created an interface just to store the value of the currentUser key from localStorage. How should implement it?

Here's the current code:

Service

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Md5 } from 'ts-md5/dist/md5';

import { User } from './user';
import 'rxjs/add/operator/map';

@Injectable()
export class VehicleService {
    private defUrl = 'dummy-url.com';

    constructor(private http: Http) { }
    getVehicle(username?: string, password?: string) {
        const url = (!username || !password) ? this.defUrl : 'dummy-url.com' + username + '/' + Md5.hashStr(password);
        return this.http.get(url)
            .map(res => res.json());
    }

    parseUser(): any {
        return JSON.parse(localStorage.getItem('parseUser'));
    }

    getUser(): any {
        return localStorage.getItem('currentUser');
    }
}

Login Component

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Location } from '@angular/common';
import { Router } from "@angular/router"

import { VehicleService } from './vehicle.service';
import { User } from './user';

@Component({
    selector: 'login',
    templateUrl: './login.html',
    providers: [VehicleService]
})
export class LoginComponent implements OnInit {
    public user: FormGroup;

    ngOnInit() {
        this.user = new FormGroup({
            username: new FormControl('', Validators.required),
            password: new FormControl('', Validators.required)
        });
    }

    constructor(public vehicleService: VehicleService, private location: Location, private router: Router) {
    }

    onSubmit(user) {
        this.vehicleService
            .getVehicle(user.value.username, user.value.password)
            .subscribe(user => {
                this.user = user;
                localStorage.setItem('parseUser', JSON.stringify(this.user));
                this.router.navigate(['/vehicle']);
                console.log('submit');
            });
        localStorage.setItem('currentUser', user.value.username);
    }

    goBack(): void {
        console.log("Back button");
        this.location.back();
    }
}

Vehicle Component

import { Component, enableProdMode, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup } from '@angular/forms';

import { VehicleService } from './vehicle.service';
import { User } from './user';
import { LoginComponent } from './login.component';

enableProdMode();

@Component({
  selector: 'vehicle-json',
  templateUrl: './vehicle.html',
  providers: [VehicleService]
})
export class VehicleComponent implements OnDestroy {
  public vehicles: GeneralVehicle[];
  public currUser: CurrentUser;

  ngOnDestroy() {
    localStorage.removeItem('currentUser');
  }


  constructor(private vehicleService: VehicleService, private router: Router) {
    this.vehicleService.getVehicle().subscribe(vehicle => {
      this.vehicles = vehicle;
      this.vehicles = this.vehicleService.parseUser();
      //this.vehicles = this.vehicleService.parseUser();
    });
    let currUser = this.vehicleService.getUser();
  }

  toLogin(): void {
    console.log("toLogin button");
    this.router.navigate(['/login']);
    localStorage.removeItem('parseUser');
    localStorage.removeItem('currentUser');
  }

}

interface GeneralVehicle {
  status: number;
  dallases: Vehicle[];
}

interface Vehicle {
  vehicle_id: number;
  dallassettings: string;
  dallasupdated: string;
  dallas_list: DallasList[];
}

interface DallasList {
  number: number;
  auth: number;
}

interface CurrentUser {
  usr: string;
}

Template: vehicle.html

<button class="btn btn-default" type="button" (click)="toLogin()">Login</button>
<div *ngIf="vehicles">
    <b>Status: {{vehicles?.status}} for user: DISPLAY-USER-HERE</b>
    <div class="list-group" *ngFor="let vehicle of vehicles.dallases" id="d1">
        <a class="list-group-item">
            <h4 class="list-group-item-heading" id="l1">Vehicle ID: {{vehicle.vehicle_id}}</h4>
        </a>
        <a class="list-group-item">
            <h4 class="list-group-item-heading">Dallas settings: {{vehicle.dallassettings}}</h4>
        </a>
        <a class="list-group-item">
            <h4 class="list-group-item-heading">Dallas updated: {{vehicle.dallasupdated}}</h4>
        </a>
        <a class="list-group-item">
            <h4 class="list-group-item-heading">Dallas list:</h4>
            <p class="list-group-item-text" *ngFor="let d of vehicle.dallas_list">
                <b>Number:</b> {{d.number}}<br>
                <b>Auth:</b> {{d.auth}}</p>
        </a>
    </div>
</div>

回答1:

You can use a getter to get the value from localStorage and show it in your template. Define it like bellow in the component class of your template.

get user(): any {
    return localStorage.getItem('currentUser');
}

In you template:

<b>Status: {{vehicles?.status}} for user: {{user}}</b>


回答2:

you have to set item in one component and get item in wherever you want. you can set item in login component and get item in vehicle component.

var user = localstorage.getitem('currentuser');

in component file.

in template: <b>{{user}}</b>



回答3:

first think this is a json stringif not a single string .ok

users = localStorage.getItem('currentUser')? JSON.parse(localStorage.getItem('currentUser')):[];
in the ts.component

call by {user.id}