Javascript 如何在Angular 4.4.6中设置本地存储项?

Javascript 如何在Angular 4.4.6中设置本地存储项?,javascript,html,angular,Javascript,Html,Angular,我正在Angular 4.4中开发一个简单的身份验证。Mongodb是我的数据库 login.component.ts auth.service.ts 我上面有一段代码,应该使用函数storeUserMeta将id_token和user设置为localStorage 我没有看到分配给JWT FKLSKFLDSKL45354L5K40FKDLKKFDLGFKDLG0945305的密钥id_令牌;FDL;flsd;flsd;FJFKDJSKFJDSKF4983432和分配给{id:123456789

我正在Angular 4.4中开发一个简单的身份验证。Mongodb是我的数据库

login.component.ts

auth.service.ts

我上面有一段代码,应该使用函数storeUserMeta将id_token和user设置为localStorage

我没有看到分配给JWT FKLSKFLDSKL45354L5K40FKDLKKFDLGFKDLG0945305的密钥id_令牌;FDL;flsd;flsd;FJFKDJSKFJDSKF4983432和分配给{id:123456789,名称:Carlo K,用户名:carlok,电子邮件:carlok@gmail.com}在

Chrome检查元素>应用程序>本地存储


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

您是否扩展了本地存储

看看下面的StackBlitz示例:


我不熟悉angular,但我记得,大多数情况下,您需要通过$window.localStorage.setItem引用当前窗口,可以尝试一下吗?是的。我扩展了该区域,但我没有看到id_令牌密钥和用户密钥。问题解决了吗?因为你把它标记为已解决。
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
      }
    });

  }

}
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
  }

}
{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
export class AppComponent implements OnInit  {
  name = 'Angular';

  ngOnInit() {
    localStorage.setItem('user', JSON.stringify({id: "123456789", name: "Carlo K", username: "carlok", email: "carlok@gmail.com"}));
  }
}