Angular2如何在HTML5模板中显示localStorage值?

时间:2017-02-07 10:13:14

标签: html5 angular local-storage angular2-forms

我在localStorage中存储了2个键,我想在我的模板中显示其中一个键。我无法访问这些值。我甚至创建了一个接口,只是为了存储localStorage中currentUser键的值。应该如何实施呢?

这是当前的代码:

服务

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');
    }
}

登录组件

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

车辆组件

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

模板: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>

3 个答案:

答案 0 :(得分:16)

您可以使用getter从localStorage获取值并在模板中显示它。在模板的组件类中将其定义为bellow。

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

在你的模板中:

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

答案 1 :(得分:0)

您必须在一个组件中设置项目并在任何地方获取项目。您可以在登录组件中设置项目并获取车辆组件中的项目。

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

在组件文件中。

模板中的

<b>{{user}}</b>

答案 2 :(得分:0)

首先认为这是一个json字符串,如果不是单个字符串。确定

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

由{user.id}呼叫