如何在Angular 4.4.6中设置localStorage项目?

时间:2018-08-21 06:15:43

标签: javascript html angular

我正在Angular 4.4中开发一个简单的Authentication。 Mongodb是我的数据库。

login.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'app/services/auth.service';
....

@Component({
  ....
})
export class LoginComponent implements OnInit {

  username: String;
  password: String;

  constructor(
  ....
  ) { }

  ngOnInit() {
  }

  onLoginSubmit() {
    console.log(this.username);
    const user = { 
      username: this.username,
      password: this.password
    }
    this.authService.authenticateUser(user).subscribe(data => {
      console.log(data);
      if(data.success) {
        this.authService.storeUserMeta(data.token, data.user);
        this.router.navigate(['admin']); //redirect
      } else {
        this.router.navigate(['login']); //redirect
      }
    });

  }

}

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class AuthService {

  authToken: any;
  user: any;

  constructor(private http:HttpClient) { }

  authenticateUser(user) {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    return this.http.post<any>('http://localhost:3000/users/authenticate', user, {headers: headers});
  }

  storeUserMeta(token, user) {
    this.authToken = token;
    this.user = user
  }

}

调用onLoginSubmit()时,我正在创建一个对象。该用户对象将被提交到后端身份验证路由的auth服务。

我试图在 login.component.ts 中打印data,这是我看到的:

{success: true, token: "JWT fklskfldskfldskl45354l5k40fkdlgkfdlgfkdlg0945305;fdls;flsd;flsd;fjfkdjskfjsdkfjdskf49832432", user: {…}}
success: true
token: "JWT fklskfldskfldskl45354l5k40fkdlgkfdlgfkdlg0945305;fdls;flsd;flsd;fjfkdjskfjsdkfjdskf49832432"
user :{id: "123456789", name: "Carlo K", username: "carlok", email: "carlok@gmail.com"}
__proto__
:
Object

我上面有一个代码,应该使用功能id_tokenuserstoreUserMeta()设置为localStorage

中,看不到分配给id_token的密钥JWT fklskfldskfldskl45354l5k40fkdlgkfdlgfkdlg0945305;fdls;flsd;flsd;fjfkdjskfjsdkfjdskf49832432和分配给user的密钥{id: "123456789", name: "Carlo K", username: "carlok", email: "carlok@gmail.com"}
  

Chrome检查元素>应用程序> LocalStorage

任何想法都值得赞赏。谢谢

1 个答案:

答案 0 :(得分:1)

您是否扩展了本地存储?

enter image description here

看下面这个StackBlitz示例:LocalStorage example

Span<T>

enter image description here enter image description here