我试图在角度6中创建动态路由,我有一个JSON文件,其中我已指定路径和组件名称,并尝试加载到app-routing文件。
JSON:
[{
"path": "home",
"component": "HomeComponent",
"Text" :"HomePage"
},
{
"path": "contactus",
"component": "ContactUsComponent",
"Text" :"ContactUsPge"
}
]
APP-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule, Router } from '@angular/router';
import { HttpErrorResponse, HttpClient } from '@angular/common/http';
const routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
Data: any;
constructor(router: Router, private httpService: HttpClient) {
const config = router.config;
this.httpService.get('./assets/dynamicRoute.json').toPromise().then(
data => {
this.Data = data as string[];
console.log(this.Data);
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
).then(i => {
this.Data.forEach(element => {
config.push(element);
router.resetConfig(config);
});
});
}
}
我已将这些组件添加到app.module.ts文件中。
entryComponents: [HomeComponent, ContactUsComponent]
另外,我不确定这种方法是否正确?任何其他建议也欢迎。 :)
遗憾的是,这种方法不会像您创建它一样。
然而,您可以(错误地)使用APP_INITIALIZER
来获取您的路线,然后路由器才会开始,创建一个可以用Router.forRoot(routes)
产生的工厂。
请记住,Route
没有物业Text
。该组件也必须是Type而不是字符串。因此,您必须根据字符串获取正确的类型。
我认为你可以通过使用自定义UrlMatcher
实现你想要的。你可以在Angular docs here中阅读它。