[英]Angular 12 SSR - routes having canActivate does not work on page reload
我有 Angular 12 項目,我在其中應用了 Angular 通用(ssr)。 我已經在 nginx 服務器上部署了該項目。
應用程序工作正常,但如果用戶按瀏覽器重新加載我已應用 canActivate 的路線不會正確重新加載。
app.routing.module.ts
{ path: "user-profile", component: UserProfileComponent,canActivate : [AuthGuard] },
auth.guard.ts
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean | UrlTree {
if (!this.authService.isLoggedIn()) {
this.openConfirmationDialog(route);
return false;
}
return true;
}
openConfirmationDialog(route) {
Swal.fire({
title: this.title,
text: this.text,
//icon: 'warning',
showCancelButton: true,
confirmButtonText: this.okButton,
cancelButtonText: this.cancelButton
}).then((result) => {
if (result.value) {
this.navigation(route)
} else if (result.dismiss === Swal.DismissReason.cancel) {
}
});
}
navigation(route) {
console.log('User confirmed:');
this.router.navigate(['login'], { queryParams: { retUrl: route.url } });
}
auth.service.ts
login(email: string, password: string) {
let input = new FormData();
const headers = {
"APP-TOKEN": "GV5TmkI8lCyPqBTLExji",
"Accept-Language": this.currentLang,
};
input.append("email", email);
input.append("password", password);
return this.http
.post<any>(`${this.serverUrl}api/v1/login`, input, { headers: headers })
.pipe(
map((user) => {
return user;
}),
catchError(this.handleError)
);
}
isLoggedIn() {
if (localStorage.getItem("currentUser")) {
return true;
}
return false;
}
在登錄表單上提交
onSubmit() {
this.submitted = true;
this.errorMessage = "";
this.isErrorOccured = false;
if (this.loginForm.invalid) {
this.errorMessage = "Invalid details";
return;
}
this.loading = true;
if (!this.localFlag) {
this.authService
.login(this.f.email.value, this.f.password.value)
.subscribe(
(data) => {
if (data["status"] === true || data["count"] === true) {
this.loading = false;
this.errorMessage = "";
this.isErrorOccured = false;
window.localStorage.setItem(
"currentUser",
JSON.stringify(data["data"])
);
window.localStorage.setItem("isLoggedIn", "true");
window.localStorage.removeItem("guest-user-id");
localStorage.setItem("loginCall", "true");
this.router.navigate(['/user-timeline']);
} else {
this.notifyService.showError(data["message"], "");
this.isErrorOccured = true;
this.loading = false;
window.localStorage.setItem("isLoggedIn", "false");
}
},
(error) => {
console.log("error:", error);
this.loading = false;
window.localStorage.setItem("isLoggedIn", "false");
}
);
} else {
}
}
如果我在頁面重新加載時檢查 localstorage currentUser
值,那么它會給出null
。 我搜索並應用rxjs
技術、 ngrx
、 ngxs
來保留價值,但這在我的項目流程中也不起作用。
我應該怎么辦 ? 還有其他方法可以驗證路由的身份驗證嗎? 或者我應該如何在頁面重新加載時保留值?
請幫助和指導。 謝謝
SSR 的意思是“服務器端渲染”,這意味着您的 Angular 代碼正在服務器中執行,然后生成的 HTML 被發送到瀏覽器。
發生了什么
當您重新加載頁面時,瀏覽器會向 URL 發出 get 請求。 與該請求一起,本地存儲數據不會發送到服務器(只有在該域上設置的 cookie 會發送到服務器)。 這就是為什么當服務器執行 AuthGuard 並且當 AuthService 嘗試讀取本地存儲時,本地存儲為空,因此預期的用戶數據為空。
解決方案
不要使用本地存儲來存儲用戶數據,而是使用 cookie。 要與 cookie 交互,您可以使用ngx-cookies 。 該軟件包還支持 SSR。 您可以在此處閱讀有關 cookie 的更多信息。 還要注意 cookie 的限制(鏈接)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.