【问题标题】:In Angular 6, providing route path via array throw error在 Angular 6 中,通过数组抛出错误提供路由路径
【发布时间】:2019-02-06 15:37:27
【问题描述】:

我是 Angular 6 应用程序,我从服务类传递角度路由格式

{ text: string, path: string }

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

我坚信与数组结构有关,需要将其传递给router.config.unshift。 unshift 方法接受路由器数组,我在其中传递任意数组......

错误

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

TypeError:无法读取未定义的属性“拆分” 在 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}
);*/

【问题讨论】:

    标签: angular angular-routing


    【解决方案1】:

    试试destructuring assignment:

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

    【讨论】:

    • 这确实有效,但没有真正了解发生了什么以及三个点如何帮助
    • 对于这种情况,解构赋值会从数组中解包值。只需单击答案上的链接即可阅读更多信息。
    猜你喜欢
    • 2018-12-27
    • 1970-01-01
    • 2019-11-19
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多