如何解决来自Json的Angular中的动态路由
所以我有一个重要的问题。是否可以在Angular 10中实现异步路由? 我已经在Angular2中阅读了有关AsyncRoute的内容,但是在Angular 10中已经不存在了。
我的代码如下:
getRoutes() {
return this.http.get(this.APIROOT + 'routes');
}
pageService.getRoutes().subscribe( (pageRoutes:RouteInterface[]) => {
const componentMap = {
'PageComponent': PageComponent,'BlogComponent':BlogComponent
};
for(let route of pageRoutes){
this.routes.push({ 'path' : route.route,'component' : componentMap[route.component]})
}
})
这将导致有效和正确的:Route Array。我的问题是此数据不是同步的。它是异步的。所以我不能通过构造函数将数据推送到app-routing.module.ts中的route:Routes Array。 还有其他方法可以实现吗?有人有经验吗?
解决方法
我想没人会回答这个问题。所以我会自己回答我的问题。我找到了解决该问题的方法。用哪种语言来编写API,但是我用Python(Django DRF + Wagtail)编写了我的语言,因此我在post_save上使用了信号钩子。每次保存页面模型对象时,我都会将所有页面对象保存到JSON文件中。该文件将保存到Angular Project Directory中。我将从目录中提取json的内容,并动态地通过此方法进行路由。
这是我的AppComponent中的代码:
export class AppComponent implements AfterViewChecked{
routes:RouteInterface[] = routes;
routeArr: Routes = [
];
constructor(private router:Router) {
const componentMap = {
'PageComponent': PageComponent,'BlogComponent':BlogComponent
};
for(let route of this.routes){
this.routeArr.push({ 'path' : route.route,'component' : componentMap[route.component]})
}
console.log(this.routeArr)
this.router.resetConfig(this.routeArr)
}
ngAfterViewChecked() {
this.router.resetConfig(this.routeArr)
}
}
线程可以关闭。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。