我创建了一个将令牌存储在本地存储中的登录名。我创建的注销按钮应从本地存储中删除此令牌,并将用户设置为null,但不会这样做,并且用户保持登录状态。
这是navbar.component.ts中的方法
onLogoutClick(){
this.authService.logout();
this.flashMessage.show('You are logged out', {
cssClass:'alert-success',
timeout: 3000
});
这是navbar.component.html中的注销链接:
<li><a class="nav-link" (click)="onLogOutClick()" href="#">Logout</a></li>
auth.service.ts:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { map } from 'rxjs/operators';
import { tokenNotExpired } from 'angular2-jwt';
@Injectable({
providedIn: 'root'
})
export class AuthService {
authToken: any;
user: any;
localUrl : string = 'http://localhost:3000/api/users';
constructor(private http: Http) { }
registerUser(user){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/users/register', user, {headers: headers})
.pipe(map(res => res.json()));
}
authenticateUser(user){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/users/authenticate', user, {headers: headers})
.pipe(map(res => res.json()));
}
storeUserData(token, user){
localStorage.setItem('token', token);
localStorage.setItem('user', JSON.stringify(user));
this.authToken = token;
this.user = user;
}
loggedIn(){
return tokenNotExpired();
}
logout(){
this.authToken = null;
this.user = null;
localStorage.clear();
}
getProfile(){
let headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/users/profile', {headers: headers})
.pipe(map(res => res.json()));
}
loadToken(){
const token = localStorage.getItem('token');
this.authToken = token;
}
}
答案 0 :(得分:2)
如syed-mohamed-aladeen所述,您的问题是您将函数命名为onLogoutClick
,但绑定到点击事件onLogOutClick
,但大写O。
函数区分大小写。
答案 1 :(得分:0)
尝试使用
window.localStorage.clear();
您的处理程序的上下文可能正在影响它。除了清除本地存储,您还应该有选择地删除项目。
logout(){
this.authToken = null;
this.user = null;
localStorage.removeItem('token');
localStorage.removeItem('user');
}