gpt4 book ai didi

javascript - 在未经授权的响应上显示登录模式 Angular 7

转载 作者:行者123 更新时间:2023-12-02 23:25:08 24 4
gpt4 key购买 nike

每次服务器返回 http 未经授权的状态 (401) 时,我都需要显示登录模式,在这种情况下,停止页面加载...例如,我已登录但试图访问 protected 资源只有管​​理员用户才能做到这一点。所以在这种情况下,我想向用户显示一个带有登录名和密码的模式。例如,它可能是在导航到 protected 路线或删除事件时。

我尝试在 ApiInterceptor 中执行此操作:

@Injectable({providedIn: 'root'})
export class ApiInterceptor implements HttpInterceptor {

constructor(
...
) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

req = req.clone({ url: environment.baseUrl + req.url });

if (this.authService.validToken) {
req = req.clone({ headers: req.headers.set('Authorization', `Bearer ${this.authService.validToken}`) });
}

if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}

return next.handle(req).pipe(catchError(resp => this.handleError(resp)));

}

private handleError(httpError: HttpErrorResponse) {
if (httpError.status === this.UNAUTHORIZED) {
// opening login modal here, but can't stop the request to prevent user to se unauthorized data, and after login, how can I redirect user to the same resource he tried to access?
}
return throwError(httpError);
}

}

这里需要帮助,如果有人知道如何做,我们将不胜感激!

最佳答案

您的 ApiInterceptor 看起来像是用于向请求添加不记名 token 。我将其称为TokenInterceptor或类似的,并创建一个新的来处理未经授权的请求。

我将创建一个新的拦截器并将其命名为UnauthorizedRequestInterceptor。与此类似的东西:

@Injectable({ providedIn: 'root' })
export class UnauthorisedRequestInterceptor implements HttpInterceptor {

constructor(private router: Router) { }

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
map(event => {
return event;
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
this.router.navigate(['/auth/login']);
}
return throwError(error);
})
);
}
}

这将拦截每个http请求,如果返回的状态为401,它将重定向到您的登录页面。

然后将其添加到 app.module.ts 中的提供程序列表中:

providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: UnauthorisedRequestInterceptor,
multi: true
}
]

至于重定向用户访问 protected 路由,这应该在您的身份验证防护中完成。

关于javascript - 在未经授权的响应上显示登录模式 Angular 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56772573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com