如何在Angular 2中将令牌详细信息设置到另一个页面

时间:2017-12-20 05:25:39

标签: angular

在我的Angular2应用程序中,我可以使用jwt成功登录。登录后,我将导航到个人资料页面。我需要在个人资料页面上显示登录用户的名字和姓氏。由于我是Angular的新手,我需要一些帮助。

这是我的login.component.ts

import {Response} from '@angular/http';
import { Component, OnInit } from '@angular/core';
import { ApiServiceProvider } from '../services/api.service';
import 'rxjs/add/operator/map';
import { Router,Routes,ActivatedRoute } from '@angular/router'

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  public user: any = {};

  constructor(private api: ApiServiceProvider,
    private router: Router
  ) { }

  ngOnInit() {
  }

  public onFormSubmit({ value, valid}: { value: any, valid: boolean }) {
    this.user = value;
    this.api.post("/account/login", value, false)
    .subscribe((data) => {
      alert("login success "+ data.token);
      localStorage.setItem("token", data.token);
      this.router.navigate(['profile']);
    }, (err) => {
      alert("login failed "+ err);
    })
  }

}

我应该在profile.component.tsprofile.component.html中添加什么来完成此操作?

1 个答案:

答案 0 :(得分:0)

假设令牌中返回first_namelast_name。你可以得到细节 从令牌中显示并在html中显示如下:

profile.component.html

<div> First Name: {{accountDetails.first_name}}</div>
<div> Last Name: {{accountDetails.last_name}}</div>

profile.component.ts

import { JwtHelper } from 'angular2-jwt';
// other things omitted for brevity 

export class ProfileComponent implements OnInit {
    private jwtHelper: JwtHelper = new JwtHelper();
    public accountDetails: any = {}

    ngOnInit() {

        try {
            const access_token = localStorage.getItem("token");
            this.accountDetails = this.jwtHelper.decodeToken(access_token).identity;
            // Verfiy that the names of keys are actually first_name and last_name
            // In case they are different change in html
            console.log("token", this.accountDetails);
        } catch (err) {
            // Access token is not proper, maybe it was tampered with
            // implement logic for logging out user
        }
    }
}

通常整个应用程序都需要名称这样的东西,所以在服务中实现解码令牌逻辑并将其存储在带有getter的服务中的私有变量中是个好主意,所以你不要这样做。必须在每个组件中解码它。