sorry about my english. I use sessionstorage for keeping data. In sessionstorage have data enter image description here
but in html, not showing data form sessionstorage. when I get only {{currentUser}} in html show like this enter image description here mycode services
import { Injectable } from '@angular/core'; const USER_KEY = 'auth-user'; @Injectable({ providedIn: 'root' }) export class TokenStorageService { constructor() { } signOut(): void { window.sessionStorage.clear(); } public saveUser(user: any): void { window.sessionStorage.removeItem(USER_KEY); window.sessionStorage.setItem(USER_KEY, JSON.stringify(user)); } public getUser(): any { const user = window.sessionStorage.getItem(USER_KEY); if (user) { return JSON.parse(user); } return {}; } }
html
<div class="container" *ngIf="currentUser; else loggedOut"> <header class="jumbotron"> <h3> <strong>{{ currentUser.employee_code }}</strong> Profile </h3> </header> <p> <strong>Token:</strong> {{ currentUser.accessToken.substring(0, 20) }} ... {{ currentUser.accessToken.substr(currentUser.accessToken.length - 20) }} </p> <p> <strong>Emp:</strong> {{ currentUser }} </p> </div> {{ currentUser }} <ng-template #loggedOut> Please login. </ng-template>
and component
import { Component, OnInit } from '@angular/core'; import { TokenStorageService } from '../../../services/token-storage.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { currentUser: any; constructor(private token: TokenStorageService) { } ngOnInit(): void { this.currentUser = this.token.getUser(); console.log(this.currentUser = this.token.getUser()) } }
how i can do to use please help me
this image for {{ currentUser|json}} {{ currentUser|json}}
Advertisement
Answer
In TokenStorageService
change getUser()
method.
public getUser(): any { return JSON.parse(window.sessionStorage.getItem(USER_KEY)); }
In HTML you are printing {{ currentUser }}
Which will be an object. You need to specify the property of object.
Note: If you want to see the object in html use json
pipe. ({{ currentUser | json }}
)