如何在 Aurelia 中按请求 URL 显示未经授权的视图

How to show an unauthorized view at the requested URL in Aurelia

如果在 Aurelia canActivate 方法内部,则确定用户不应能够查看请求的页面。如何向该用户显示 "Unauthorized" 页面,在 URL 他们不允许访问?

我不想 return 一个 new Redirect("#/unauthorized") 因为这样用户就看不到哪些 URL 他们不被允许访问而且我在URL 会丢失。

注意:可能的答案可能是 "You are doing this all wrong"。 :)

您想在不更改 URL 的情况下显示未经授权的页面。因此,如果用户访问“/restricted-page”并且不允许他们看到它,则显示未经授权的模板而不是实际页面。

为此,如果用户未通过适当的检查,您可以在 canActivate 方法中为 ViewModel 本身设置一个模板值。然后在您的 ViewModel 的 getViewStrategy 中,您将检查是否已设置此值并显示该视图,如果没有,则显示您的常规视图。

export class ViewModel {
  viewTemplate = "./view-model.html";

  canActivate(params, routeConfig) {
    if (!canViewPage) {
      this.viewTemplate = "./401-unauthorized.html";
    }
  }

  getViewStrategy() {
    return this.viewTemplate;
  }  
}

为了进一步简化,您只需在 canActivate.

内部设置 getViewStrategy 函数本身
export class ViewModel {
  canActivate(params, routeConfig) {
    if (!canViewPage) {
      this.getViewStrategy = function() { return "./401-unauthorized.html"; };
    }
  }
}