我正在AuthGuard為我的應用程式創建一個..現在當我嘗試加載組件而不登錄時,它應該將我重定向到登錄頁面..但是我收到如下錯誤

沒有任何反應。
我從后端拋出這個錯誤,{"status":401,"message":"Auth Token Not found!"}}
因為沒有授權令牌
以下是我的代碼AuthGuard
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> {
return this.authService.checkLogin().pipe(
map((data: HttpResponse) => {
if (data.status == 200) {
console.log("OUTPUT:", data)
return true
}
else return false
}),
)
}
}
以下是我的功能AuthService:
public checkLogin():Observable<HttpResponse> {
return this.http.get<HttpResponse>('http://localhost:5000/auth/check-login', { withCredentials: true })
}
現在我如何處理這些錯誤并將回退值設定為false所以如果發生任何錯誤則無法訪問該路由
uj5u.com熱心網友回復:
如果我對您的理解正確,您希望實作以下行為:
- 如果
checkLogin()收到指示“成功”的回應,則 auth-guard 應回傳true - 如果
checkLogin()得到錯誤回應,將用戶重定向到后備頁面并回傳false
如果您使用下面的代碼,請注意catchError()僅當后端回應例外時才會觸發,而如果從后端回傳map()成功回應則始終觸發。因此,在肯定的情況下,您可以簡單地回傳true而不檢查回應的內容。但是,如果您從后端收到例外,您可以將用戶重定向到后備頁面this.router.navigate(),然后回傳of(false)以防止請求通過身份驗證保護。
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> {
return this.authService.checkLogin().pipe(
map(() => true),
catchError(() => {
this.router.navigate(['route-to-fallback-page']);
return of(false);
})
);
}
}
Angular 7.1 的替代解決方案
從 Angular 7.1 開始,你可以只回傳一個UrlTree包含回退路由的物件:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> {
return this.authService.checkLogin().pipe(
map(() => true),
catchError(() => this.router.parseUrl('/route-to-fallback-page'))
);
}
uj5u.com熱心網友回復:
您可以使用共享錯誤回應
this.http.get<HttpResponse>('http://localhost:5000/auth/check-login', { withCredentials: true }).pipe(
catchError((error=>{
this.getErrorMessage(error);
return throwError(()=>error);
}))
)
getErrorMessage 函式將回傳錯誤;
private getErrorMessage(error:HttpErrorResponse){
switch(error.status){
case 400:{
return this.toast.error(`Bad Request :${JSON.stringify(error.error?.Message)}`,error.status.toString())
}
case 401:{
return this.toast.error(`Unauthorized :${JSON.stringify(error.error?.Message)}`,error.status.toString())
}
case 403:{
return this.toast.error(`Access Denied :${JSON.stringify(error.error?.Message)}`,error.status.toString())
}
case 500:{
return this.toast.error(`Internal Server Error :${JSON.stringify(error.error?.Message)}`,error.status.toString())
}
case 404:{
return this.toast.error(`Page Not Found :${JSON.stringify(error.error?.Message)}`,error.status.toString())
}
default:{
return this.toast.error('Check your internet connection!');
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/537504.html
上一篇:選中mat-checkbox時,AngularArray.push僅推送陣列中的最后一個物件
下一篇:根據@input設定組件提供者
