我正在尝试找到一种方法来保持我的角度变量与页面刷新/跨组件。我的工作流程是
Al可以正常工作。当用户登录并获取访问令牌并将此令牌保存在localstorage中时。应用程序将用户重定向到仪表板组件。
但是问题是,如果刷新页面,则本地存储将变为空白,并且应用程序会将用户重定向到登录页面。
我对angular还是很陌生,无法找到一种方法来刷新页面后保留任何数据。
dashboard.component.ts
auth.service.ts
jwt.interceptor.ts
auth.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Signin, ResetPassword } from '../model/user.model';
import { Router } from '@angular/router';
@Injectable()
export class AuthService {
private URL_Register = 'http://localhost:52718/account/register'; //Register User (Working)
private URL_Signin = 'http://localhost:52718/account/Signin'; // Login User (Working)
private URL_Token = 'http://localhost:52718/connect/token'; // Get Token Against Register User (Working)
private URL_Data = 'http://localhost:52718/api/values'; // Get Token Against Register User (Working)
private URL_Claims = 'http://localhost:52718/account/Get';
private URL_PasswordRecovery = 'http://localhost:52718/account/ForgotPassword';
private URL_ChangePassword = 'http://localhost:52718/account/ChangePassword';
public isUserAuthenticated: boolean = false;
private loggedIn = new BehaviorSubject<boolean>(false); // {1}
get isLoggedIn() {
return this.loggedIn.asObservable(); // {2}
}
constructor(
private http: HttpClient,
private router: Router) { }
userAuthentication(credientials: Signin) {
let reqHeader = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.post(this.URL_Signin, JSON.stringify(credientials), { headers: reqHeader }).subscribe((data: any) => {
localStorage.setItem('userToken', data.token);
this.loggedIn.next(true);
this.router.navigate(['/dashboard']);
},
(err: HttpErrorResponse) => {
console.log('Auth Service (Method userAuthentication): [HttpError] ' + err.message)
});
}
fetchData() {
return this.http.get(this.URL_Data);
}
getUserClaims() {
return this.http.get(this.URL_Claims);
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('userToken');
this.loggedIn.next(false);
this.router.navigate(['/login']);
}
forgotPassword(ResetPassword: ResetPassword) {
let reqHeader = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.post(this.URL_PasswordRecovery, JSON.stringify(ResetPassword), { headers: reqHeader }).subscribe((data: any) => { },
(err: HttpErrorResponse) => {
console.log('Auth Service (Method userAuthentication): [HttpError] ' + err)
});;
}
changePassword(QueryParams: Object) {
let reqHeader = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.http.put(this.URL_ChangePassword, JSON.stringify(QueryParams), { headers: reqHeader }).subscribe((data: any) => {
localStorage.setItem('userToken', data.token);
this.loggedIn.next(true);
this.router.navigate(['/dashboard']);
},
(err: HttpErrorResponse) => {
console.log('Auth Service (Method changePassword): [HttpError] ' + err)
});;
}
}
答案 0 :(得分:0)
我想知道如果我更改下面的代码
get isLoggedIn() {
return this.loggedIn.asObservable(); // {2}
}
进入
get isLoggedIn() {
let currentUser = localStorage.getItem('userToken');
if (!currentUser) { }
this.loggedIn.next(true);
return this.loggedIn.asObservable();
}
现在我不需要重新登录,本地存储也在那里。
幕后的逻辑是,正如我在上面的loginIn属性上设置为false一样,这就是为什么当我默认情况下刷新页面时,loginIn方法会在注销当前用户后将我重定向到登录页面。因此,我修改了此属性,并检查用户在浏览器本地存储中是否有令牌,然后不要重定向或不需要删除其令牌。
同时,我的问题已解决。但同时,我也在寻找更好的答案。