【问题标题】:Angular 5 - using the same path for different modulesAngular 5 - 对不同的模块使用相同的路径
【发布时间】:2018-03-09 12:10:43
【问题描述】:

如果你们碰巧是 facebook 用户,您可能会注意到在用户登录或退出时,Url“https://www.facebook.com”不会改变。我在我正在构建的应用程序中遇到了同样的问题(使用角度 5)。尽管有一些建议的解决方案:

  1. 首先是使用相同的路由,一个组件(比如:home),在 home 的模板中,我们使用 *ngIf 插入 in、out(组件),在运行时我们检查用户是否登录或退出,基于此,我们显示相应的(输入或输出)组件。

home.component.html

<app-in *ngIf="loggedIn"></app-in>
<app-out *ngIf="!loggedIn"></app-out>
  1. 我认为会更简洁的第二种方法,尤其是在使用 延迟加载 时,是连续有两条具有相同空路径的路由,并使用 ma​​tcher,现在老实说这仍然很难看,因为 matcher 不适合这种高级用途(它也是同步的,并且不包含在服务中 - 例如 canLoadcanActivate..etc- 可以很容易地注入一些其他服务(例如:authService)来检查一个人是否登录或退出)。

home.routing.ts

.
.
.

const routes: Routes = [
  {
    matcher: matcherFunc,
    loadChildren: './in/in.module#InModule'
  },
  {
    path: '',
    loadChildren: './out/out.module#OutModule'
  }
];

.
.
.

这是匹配函数:

export function matcherFunc(url: UrlSegment[]) {
  let currentUser;


    currentUser = localStorage.getItem('user');

  if (url.length === 0 && currentUser) {
    return ({ consumed: url });
  } else {
    return null;
  }
}

当我将我的应用升级为通用时,问题变得更加严重,因为在那种情况下,我不得不在服务器端处理全局变量(window、localStorage..etc) 我被完全困住了!

我相信这个问题已经存在了一段时间了,没有令人满意的答案,有什么建议吗?

【问题讨论】:

    标签: angular angular5 server-side-rendering angular-universal


    【解决方案1】:

    您可以使用一个模块来处理应该加载的模块,方法是使用 Angular 的 useFactory 提供程序提供 RouterModule 的 ROUTES。

    代码可能是这样的。

    // HandlerModule
    
    @NgModule({
      declarations: [],
      imports: [
        CommonModule,
        RouterModule
      ],
      providers: [
        {
          provide: ROUTES,
          useFactory: configHandlerRoutes,
          deps: [SessionService],
          multi: true
        }
      ]
    })
    
    
    export class HandlerModule {}
    
    export function configHandlerRoutes(sessionService: SessionService) {
      let routes: Routes = [];
      if (sessionService.isLoggedIn()) {
        routes = [
          {
            path: '', loadChildren: './in/in.module#InModule'
          }
        ];
      } else {
        routes = [
          {
            path: '', loadChildren: './out/out.module#OutModule'
          }
        ];
      }
      return routes;
    }
    

    那么在您的 AppRoutingModule 中,路径 '' 的模块将成为 HandlerModule:

    // AppRoutingModule
    
     {
        path: '',
        loadChildren: './handler/handler.module#HandlerModule'
     }
    

    在 SessionService 之后,当提供方法 isLoggedIn 的值发生变化时,您必须更新 Router.config,因为应用程序只会加载第一次加载的页面(模块)。这是因为 HandlerModule 中 useFactory 提供程序使用的函数“configHandlerRoutes”仅在我们第一次导航到“”路径时执行,之后 Angular 路由器已经知道他必须加载哪个模块。

    在 SessionService 中你必须做的总结:

      export class SessionService {
      private loggedIn: boolean;
      constructor(private router: Router) {
        this.loggedIn = false;
      }
    
      public isLoggedIn(): boolean {
        return this.loggedIn;
      }
    
      public setLoggedIn(value: boolean): void {
        const previous = this.loggedIn;
        this.loggedIn = value;
        if (previous === this.loggedIn) {
          return;
        }
        const i = this.router.config.findIndex(x => x.path === '');
        this.router.config.splice(i, 1);
        this.router.config.push(
          {path: '', loadChildren: () => import('app/handler/handler.module').then(mod => mod.HandlerModule)}
        );
      }
    }
    

    就是这样。

    如果您想要其他参考,请参阅他们使用相同方法的文章:https://medium.com/@german.quinteros/angular-use-the-same-route-path-for-different-modules-or-components-11db75cac455

    【讨论】:

    • 这种方法确实对我有用,但突然我不得不在提供ROUTES 令牌时将所有(非惰性)组件添加到entryComponents 数组中。你知道为什么吗?
    • 嗨@devqon,当我使用 Angular 8 时,没有必要将它们添加到 entryComponents,这是我的仓库:github.com/gquinteros93/same-path-for-different-modules 你在其他模块中使用这些组件吗?
    • 可能是因为我有点不同;有一个“遗留”组件急切地加载到路由中,但现在我想要一个开关,它会延迟加载整个功能模块。我会深入研究它,但由于子路由的其他问题,目前我不得不恢复这种方法
    • 嗨@German Quinteros 你能为此提供一个stackblitz吗?添加此解决方案后出现找不到路径的错误。
    • 嗨@mayurkukadiya,这里有带有解决方案的Github repo:github.com/gquinteros93/same-path-for-different-modules
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2015-11-03
    相关资源
    最近更新 更多