我有一个基于Angular 5和Contentful构建的应用程序。服务从Contentful作为JSON检索Entry
个路由,并且必须将这些路由提供给延迟加载的子路由模块。显然,路由需要在子路由模块中动态设置,因为它应该可以随时从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
中分配的路由NewsArticleComponent
无法识别。尽管这是@NgModule
。答案 0 :(得分:1)
我看到你要做的是什么,但是在这种情况下应该应用不同的过程
假设您有一个包含以下主要路线的网站;
/home
/home/news
/home/news/article1
/home/news/article2`
home
和home/news
将是您的RouterModule.forRoot
路线
如果文章路线被激活/home/news/article1
,则应加载NewsArticleComponent
- 您需要的是Angular Route Parameters
{ path: '/home/news/:id', component: NewsArticleComponent }
在NewsArticleComponent
的ngOnInit中,您可以获取新文章ID,并从内容中检索条目。您可能还想查看Route Resolvers
,您可以在加载新闻组件之前从Contentful中检索数据
您需要找到路线参数的示例,以及路线解析器。在那之后,它应该非常简单
注意:我不确定您为何懒惰加载新文章组件。你通常只是懒得加载不太经常使用的模块,但在这种情况下它是你应用程序的主要组件