【问题标题】:Angular: Dynamic Setting of Routes inside a Child Router Module, that is lazily-loadedAngular:延迟加载的子路由器模块内路由的动态设置
【发布时间】:2018-05-16 19:19:15
【问题描述】:

我有一个基于 Angular 5 和 Contentful 的应用程序。服务从 Contentful 检索 Entry 的路由作为 JSON,并且必须将这些路由提供给延迟加载的子路由模块。显然,路由需要在子路由模块中动态设置,因为应该可以随时从 Contentful 更新它们的值。

子路由模块 NewsRoutingModule 如下所示:

const newsRoutes: Routes = [
  { path: '', component: NewsComponent },
  { path: '**', component: 404Component }
];

@NgModule({
  imports: [
    RouterModule.forChild(newsRoutes),
    ...
  ],
  declarations: [
    NewsComponent,
    NewsArticleComponent,
    NewsCardComponent
  ],
  ...
})

export class NewsRoutingModule {

  constructor(
    private router: Router,
    private languageService: LanguageService,
    private contentfulService: ContentfulService
  ) {
    this.loadRoutes();
  }

  loadRoutes() {

    // Language Service is used to detect the locale. Contentful Service is used to pull content from Contentful.
    this.languageService.events$.subscribe(locale => {
      this.contentfulService
        .getSearchResults('newsArticle', '', locale)
        .then(response => {

          // Content from Contentful returned as a response containing an array of Entry objects.
          response.items.forEach((entry: Entry<any>) => {
            let entryRoute = entry.fields.route;
            let hasRoute = false;

            // Check that the route doesn't already exist before adding it.
            newsRoutes.forEach((angularRoute) => {
              if (angularRoute.path == entryRoute) {
                hasRoute = true;
              }
            });
            if (!hasRoute) {
              newsRoutes.push({path: entryRoute, component: NewsArticleComponent});
            }
          });

          // Reset router's config at the end.
          this.router.resetConfig(newsRoutes);
        });
    });
  }

}

我遇到了一些问题:

  1. 如果我重置路由器的配置,就像我最后所做的那样,全局路由会被重置,而不仅仅是在子路由模块NewsRoutingModule中分配的路由。
  2. 无法识别我尝试为 Contentful 中的每条新路由分配的 NewsArticleComponent。尽管它是 @NgModule 声明的一部分。

【问题讨论】:

    标签: angular rxjs angular-routing contentful


    【解决方案1】:

    我明白你在做什么,但是在这种情况下应该应用不同的过程

    假设您有一个包含以下主要路线的站点;

    /home /home/news /home/news/article1 /home/news/article2`

    homehome/news 将是您的 RouterModule.forRoot 路由

    如果文章路径被激活,/home/news/article1,这应该加载你的NewsArticleComponent - 你需要的是Angular Route Parameters

    { path: '/home/news/:id', component: NewsArticleComponent }
    

    NewsArticleComponent 的ngOnInit 中可以获取新的文章id,并从contentful 中检索Entry。您可能还想查看Route Resolvers,您可以在加载新闻组件之前从 Contentful 中检索数据

    您将需要找到路由参数的示例,以及路由解析器。之后,它应该非常简单

    注意:我不确定您为什么要延迟加载新文章组件。您通常只延迟加载不太可能经常使用的模块,但在这种情况下,它是您应用程序的主要组件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 2020-03-31
      • 1970-01-01
      相关资源
      最近更新 更多