将令牌存储在LocalStorage

时间:2019-04-24 13:53:47

标签: angular typescript ionic-framework

因此,我试图在登录身份验证后存储用户令牌,但是出了点问题,这是我的代码:

fazerLogin(){
    this.authloginService.logarConta(this.email, this.password).then((result)=>{
      console.log(result)
      localStorage.setItem('token', JSON.stringify({token: this.token}))
      console.log(this.token)
      this.navCtrl.navigateForward('home')

     }

在登录后在此处显示响应数据:

{name: "MyName", email: "my@email.com", token: "ed814437611e187679e4719d87e9dfd6e1d8c819", message: "Success."}
email: "my@email.com"
message: "Success"
name: "MyName"
token: "ed814437611e187679e4719d87e9dfd6e1d8c819"

2 个答案:

答案 0 :(得分:3)

您想要这样做:

localStorage.setItem('token', result.token)

定义此方法的位置:logarConta()

为其提供适当的返回类型,例如:

logarConta() : {nmae: string, email: string, message: string, token: string} {
    // your code
}

如果这不适合您,并且您希望将其保留为Object,请改用此方法:

localStorage.setItem('token', result['token'])

答案 1 :(得分:3)

您不必调用JSON.stringify,因为它已经是一个字符串了,

 localStorage.setItem('token', result["token"]);