Reputation: 3062
I am developing a simple Authentication in Angular 4.4. Mongodb is my database.
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
}
}
I am creating an object when onLoginSubmit()
is called. The user object will be submitted to the auth service to the backend authenticate route.
I tried to print data
in login.component.ts and this is what I see:
{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: "[email protected]"}
__proto__
:
Object
I have a code above that should set id_token
and user
to localStorage using the function storeUserMeta()
I don't see the key id_token
assigned to JWT fklskfldskfldskl45354l5k40fkdlgkfdlgfkdlg0945305;fdls;flsd;flsd;fjfkdjskfjsdkfjdskf49832432
and user
key assigned to {id: "123456789", name: "Carlo K", username: "carlok", email: "[email protected]"}
in
Chrome Inspect Element > Application > LocalStorage
Any idea is appreciated. Thanks
Upvotes: 0
Views: 80
Reputation: 2084
Did you expand the Local Storage?
Look a this StackBlitz example: LocalStorage example
export class AppComponent implements OnInit {
name = 'Angular';
ngOnInit() {
localStorage.setItem('user', JSON.stringify({id: "123456789", name: "Carlo K", username: "carlok", email: "[email protected]"}));
}
}
Upvotes: 1