会话输出后,上一个用户的凭据在页面中,而不是当前用户在 Angular 5 中



在angular 5中,当我从一个用户注销并从另一个用户登录时,在刷新页面之前,它显示的是前一个用户的凭据,而不是当前用户的凭据。我使用的是localstorage.clear()方法。仍然不起作用。

这里是登录功能

login(userLogin: LoginModel) {
const objectToSend = JSON.stringify(userLogin);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('withCredentials', 'true');
// tslint:disable-next-line:max-line-length
return this.http.post( this.appURL+'/api/auth/login', objectToSend, { headers: headers }).pipe(
map((response: Response) => {
// login successful if there's a jwt token in the response
const response_token = response.json();
console.log(response_token);
const accessToken = response_token.auth_token;
if (accessToken == null) {
throw new Error('Received accessToken was empty');
}
// let refreshToken: string = response_token.refresh_token;
const expiresIn: number = response_token.expires_in;
const tokenExpiryDate = new Date();
tokenExpiryDate.setSeconds(tokenExpiryDate.getSeconds() + expiresIn);
const accessTokenExpiry = tokenExpiryDate;
localStorage.setItem('auth_token', response_token.auth_token);
localStorage.setItem('role', response_token.role);
this.loggedIn = true;
this._authNavStatusSource.next(true);
this.router.navigate(['/orderhistory']);
return true;
}));
}

注销功能是吗

logout() {
localStorage.removeItem('auth_token');
localStorage.removeItem('role');
localStorage.clear();
sessionStorage.clear();
this.loggedIn = false;
this._authNavStatusSource.next(false);
}

这是用户角色不会相应更新的组件。

@Component({
selector: 'app-order',
templateUrl: './order.component.html',
styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit {
form: FormGroup;
currentRole: string;
constructor(private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private userService: UserService, private http: HttpClient) {
}
ngOnInit() {
this.form = this.formBuilder.group({
quantity: [null, Validators.required],
prescription: [null],
});
this.currentRole = this.userService.Role;

}
and this is the template. and this role is not updating after logout
<form [formGroup]="form" class="form-horizontal">
<span *ngIf="currentRole =='administrator'">
<div class="form-group row">
<label class="col-md-3 col-form-label">Client Name</label>
<div class="col-md-3">
<label class="col-form-label">{{orderModel.clientName}}</label>
</div>
</div>
</span>
<span>{{currentRole}}</span>
<form>

您正在清除本地存储,我怀疑您能够在Chrome Developer Tools(应用程序选项卡(中确认这些值已被清除,这就是刷新页面有效的原因。

您在屏幕上看到的是您仍然存储在组件或服务中的值的结果。

我通常的注销流程是这样的:

  1. 清除浏览器状态(您所做的操作(
  2. 清除相关的服务值。我通常在一个名为UserService的服务中管理活动用户,当注销时,该服务还会清除活动用户的姓名或用户ID等字段或存储在此处的任何其他字段
  3. 导航离开。登录时,用户通常可以查看注销后不可用的值。因此,我使用Router服务导航到用户可以再次登录的页面。对于大多数操作都需要登录用户的应用程序来说,这就足够了

我的第2步和第3步清除了屏幕,因此不再显示过时的值。步骤1确实防止了应用程序认为用户仍然有一个有效的会话。

最新更新