如何对http 401做出角度响应

Guy*_*y E 2 angular angular-router angular-guards

我有一个nodejs(express)作为服务器端,一个Angular 6作为客户端。在服务器中,我有中间件功能来进行会话检查。如果会话无效或不存在,我想向客户端发送响应,以便客户端可以对其做出反应。我想到从服务器返回401的响应代码,并在客户端中创建某种listener\route-guard\HttpInterceptor,这样 - 它可以管理客户端中的情况(例如将其重定向到登录页面) 。这是我在服务器中的代码:

router.use('/', (req, res, next) =>
{
    if (!req.session.user)
    {
        res.status(401);
    }
    else{
        next();
    }
})
Run Code Online (Sandbox Code Playgroud)

我如何在角度应用程序中捕获/收听此响应?

Pat*_*dak 5

您可以创建一个HttpInterceptor,在其中检查状态是否为 401,如果是,则注销用户并重定向到登录页面。所做HttpInterceptor的就是拦截每个请求和响应,并允许您执行一些特定操作,例如检查 servce 是否返回 401 状态。但是请注意,rangeinterceptor的工作原理是这样services的,如果您将其包含在顶级模块中,那么它将拦截每个请求和响应

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor( 
       private authService: AuthService
    ) { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            map((event: HttpEvent<any>) => event), // pass further respone
            catchError((error: HttpErrorResponse) => {
                // here will be catched error from response, just check if its 401
                if (error && error.status == 401)
                    // then logout e.g. this.authService.logout()
                return throwError(error);
            }));
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其包含在app.httpmodule提供者部分中

providers: [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptor,
    multi: true
  },
]
Run Code Online (Sandbox Code Playgroud)

阅读angular.io 文档angular.io 指南了解更多信息