【发布时间】: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);
});
});
}
}
我遇到了一些问题:
- 如果我重置路由器的配置,就像我最后所做的那样,全局路由会被重置,而不仅仅是在子路由模块
NewsRoutingModule中分配的路由。 - 无法识别我尝试为 Contentful 中的每条新路由分配的
NewsArticleComponent。尽管它是@NgModule声明的一部分。
【问题讨论】:
标签: angular rxjs angular-routing contentful