角度:检测拦截器中的重定向

时间:2018-11-20 10:42:07

标签: angular angular6

我有一个会话的应用程序,该会话在闲置20分钟后到期。该应用程序的用户非常懒惰,因此我想他们在早上喝咖啡后将继续使用该应用程序,并对与Web API的通信将引发的错误感到惊讶。我的想法是拦截会话期满后,服务器下次访问Web API可能触发的重定向到登录页面的访问。

所以我写了一个拦截器:

@Injectable()
export class SessionEndInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    {
      const initialUrl = req.url;

      return next.handle(req).pipe(
        map((event: HttpEvent<any>) => {
          const res = (event instanceof HttpResponse) && event as HttpResponse<any>;

          if (res && this.checkIfSessionEnd(initialUrl, res.url)) {
            window.location.href = this.replaceRedirectionWithCurrentLocation(
              res.url
            );
          } else {
            return event;
          }
        })
      );
    }
  }

  private checkIfSessionEnd(initialUrl: string, currentUrl: string): boolean {
    const isInitialUrlLogin = this.isLoginUrl(initialUrl);
    const isResponseUrlLogin = this.isLoginUrl(currentUrl);
    const isRedirectionToLogin = !isInitialUrlLogin && isResponseUrlLogin;
    return isRedirectionToLogin;
  }
  ...
}

但是问题是(event instanceof HttpResponse)这部分从来都不是真的,所以我不能做res.url并比较URL。我想知道如何获取响应的URL(或任何其他想法)。

更新

让我们假设会话已过期。

1-客户端(Angular)在按下按钮后向服务器发出GET请求。

2-服务器(具体为FormsAuthetication),检测到会话已过期,并发送302代码和登录页面的URL。

3-客户端看到并跟随它(无法阻止浏览器进行重定向),然后向服务器发出另一个GET请求以请求登录页面。

4-现在客户端正在接收登录页面的HTML,并引发错误,因为它正在等待JSON数据。

好吧,我想要的是,通过将初始请求的URL与当前URL进行比较,如果它们不同,并且其中之一恰好是登录页面,请使用window.location.href将客户端重定向到登录页面,因此他要继续工作就别无选择,只能再次登录。

UPDATE II

我知道无法检测到302重定向。因此,我想要将登录页面的200个响应的URL与初始响应(触发重定向到登录页面的URL)进行比较。

0 个答案:

没有答案
相关问题