如何在Angular 5中重定向到401响应的登录页面?

ilM*_*ion 6 interceptor oauth-2.0 typescript angular

我正在使用OAuth2隐式流程开发Angular 5应用程序.

我有服务执行HTTP调用,遵循我的服务示例:

@Injectable()
export class MyService {

  constructor(public http: HttpClient) { }

  public getAll(): Observable<Persona[]> {
    return this.http.get<Persona[]>("http://mywebservice/persone");
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用拦截器进行授权并添加自定义属性.跟随我的auth拦截器:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from "rxjs";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor() {

  }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let accessToken = sessionStorage.getItem("access_token");
    if(accessToken)
    {
        request = request.clone({
        setHeaders: {
            Authorization: `Bearer ${accessToken}`
        }
        });
    }

    return next.handle(request);
  }
}
Run Code Online (Sandbox Code Playgroud)

以及我如何使用我的服务:

public myMethod() {
    this.myService.getAll().subscribe(
        result => {
            console.log(result);
        }, error => {
            // I don't want add redirection there...
            console.error(error);
        });
}
Run Code Online (Sandbox Code Playgroud)

现在我需要的是,当任何HTTP调用接收到401结果时,应用程序会将用户重定向到登录页面.

如何在没有代码重复的情况下获得此结果?

非常感谢

ilM*_*ion 11

我解决了我的问题,改变我的拦截器如下:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor() {

  }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let accessToken = sessionStorage.getItem("access_token");
    if(accessToken)
    {
        request = request.clone({
        setHeaders: {
            Authorization: `Bearer ${accessToken}`
        }
        });
    }

    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
            this.router.navigate(['login']);
        }
      }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我在那里找到了解决方案:https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

  • 您从哪里获得路由器实例? (3认同)
  • 在 Angular 13 中不起作用。不支持 do 方法 (3认同)
  • 先生,这个“this.router”是从哪里来的? (2认同)

Jal*_*ini 10

仅为了支持新读者,请注意,在angular 7中,应使用pipe()而不是do()或catch():

return next.handle(request).pipe(catchError(err => {
    if (err.status === 401) {
        MyComponent.logout();
    }
    const error = err.error.message || err.statusText;
        return throwError(error);
}));
Run Code Online (Sandbox Code Playgroud)