问题描述
我在localStorage中存储了2个键,我想在我的模板中显示其中一个键。我无法访问这些值。我甚至创建了一个接口,只是为了存储来自localStorage的currentUser密钥的值。应该如何实施?
以下是当前代码:
服务
从'@ angular / core'导入{Injectable};来自'@ angular / http'的
import {Http};
从'ts-md5 / dist / md5'导入{Md5};
从'./user'导入{User};
import'rxjs / add / operator / map';
@Injectable()
导出类VehicleService {
private defUrl ='dummy-url.com';
构造函数(private http:Http){}
getVehicle(username?:string,password?:string){
const url =(!username ||!password)? this.defUrl:'dummy-url.com'+用户名+'/'+ Md5.hashStr(密码);
返回this.http.get(url)
.map(res => res.json());
}
parseUser():任何{
返回JSON.parse(localStorage.getItem('parseUser'));
}
getUser():任何{
返回localStorage.getItem('currentUser');
}
}
登录组件
从'@ angular / core'导入{Component,OnInit};来自'@ angular / forms'的
import {FormGroup,FormControl,Validators};
从'@ angular / common'导入{Location};来自@ angular / router的
import {Router}来自'./vehicle.service'的
import {VehicleService};
从'./user'导入{用户};
@Component({
selector:'login',
templateUrl:'。/ login.html',
providers:[VehicleService]
} )
导出类LoginComponent实现OnInit {
public user:FormGroup;
ngOnInit(){
this.user = new FormGroup({
username:new FormControl('',Validators.required),
密码:new FormControl( '',Validators.required)
});
}
构造函数(公共车辆服务:VehicleService,私有位置:位置,私有路由器:路由器){
}
onSubmit(用户){
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(后退按钮);
this.location.back();
}
}
车辆组件
从'@ angular / core'导入{Component,enableProdMode,OnDestroy};来自'@ angular / router'的
import {Router};来自'@ angular / forms'的
import {FormGroup};
从'./vehicle.service'导入{VehicleService};
从'./user'导入{用户};
从'./login.component'导入{LoginComponent};
enableProdMode();
@Component({
选择器:'vehicle-json',
templateUrl:'。/ vehicle.html',
提供者:[VehicleService]
})
导出类VehicleComponent实现OnDestroy {
公共交通工具:GeneralVehicle [];
public currUser:CurrentUser;
ngOnDestroy(){
localStorage.removeItem('currentUser');
}
构造函数(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 [];
}
界面车辆{
vehicle_id:number;
dallassettings:string;
dallasupdated:string;
dallas_list:DallasList [];
}
interface DallasList {
number:number;
auth:number;
}
接口CurrentUser {
usr:string;
}
模板:vehicle.html
< button class =btn btn-defaulttype =button(click)=toLogin()>登录< /按钮>
< div * ngIf =vehicles>用户的
< b>状态:{{vehicles?.status}}:DISPLAY-USER-HERE< / b>
< div class =list-group* ngFor =let vehicle of vehicles.dallasesid =d1>
< a class =list-group-item>
< h4 class =list-group-item-headingid =l1>车辆ID:{{vehicle.vehicle_id}}< / h4>
< / a>
< a class =list-group-item>
< h4 class =list-group-item-heading>达拉斯设置:{{vehicle.dallassettings}}< / h4>
< / a>
< a class =list-group-item>
< h4 class =list-group-item-heading>达拉斯更新:{{vehicle.dallasupdated}}< / h4>
< / a>
< a class =list-group-item>
< h4 class =list-group-item-heading>达拉斯列表:< / h4>
< p class =list-group-item-text* ngFor =let d of vehicle.dallas_list>
< b>数量:< / b> {{d.number}}<峰; br>
< b> Auth:< / b> {{d.auth}}< / p为H.
< / a>
< / div>
< / div>
您可以使用getter从localStorage获取值并在您的模板中显示它。在模板的组件类中将其定义为bellow。
get user():any {
return localStorage。的getItem( 'currentUser');
}
在你的模板中:
用户的{pre>
< b>状态:{{vehicles?.status}}:{{user}}< / b>
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>
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>
这篇关于Angular2如何在HTML5模板中显示localStorage值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!