在Angular 6中,通过数组抛出错误提供路由路径

时间:2019-02-06 15:37:28

标签: angular angular-routing

我是Angular 6应用程序,我正在以格式

从服务类传递角路由。
{ text: string, path: string }

所以我的想法是我动态添加路由,如果我静态地提供数据,这很好用;但是,如果我替换了与通过数组提供数据相同的结构,则会抛出错误,

我坚信与数组结构有关,需要将其传递给router.config.unshift的方式。 unshift方法接受Router的数组,而我正在传递任何的数组.......

错误

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'split' of undefined

TypeError:无法读取未定义的属性“ split”     在defaultUrlMatcher(router.js:530)

路线服务

 @Injectable({
 providedIn: 'root'
 })

export class DynamicRoutingService{

messages: string[] = [];

constructor(){}

getDynamicRoutes():any{ // need fix here to pass Route[]
 return [
    { path: 'publicSurvey', component: SurveyFormComponent },
    { path: 'RedMatter', component: SurveyFormComponent },
    { path:'waterDamAndBridge', component:SurveyFormComponent}
  ];
 }
}

应用程序组件

export class AppComponent {

 constructor(
   private router: Router,
   private routingService:DynamicRoutingService
 ){

  let dynamicRoutes = this.routingService.getDynamicRoutes();

  this.router.config.unshift(dynamicRoutes); // this line throw error


  /*  following disable code does work
   this.router.config.unshift(
  { path: 'publicSurvey', component: SurveyFormComponent },
  { path: 'RedMatter', component: SurveyFormComponent },
  { path:'waterDamAndBridge', component:SurveyFormComponent}
);*/

1 个答案:

答案 0 :(得分:1)

尝试destructuring assignment

this.router.config.unshift(...dynamicRoutes);