我正在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_token
将user
和storeUserMeta()
设置为localStorage
在
中,看不到分配给id_token
的密钥JWT fklskfldskfldskl45354l5k40fkdlgkfdlgfkdlg0945305;fdls;flsd;flsd;fjfkdjskfjsdkfjdskf49832432
和分配给user
的密钥{id: "123456789", name: "Carlo K", username: "carlok", email: "carlok@gmail.com"}
Chrome检查元素>应用程序> LocalStorage
任何想法都值得赞赏。谢谢