K.Z
K.Z

Reputation: 5075

In Angular 6, providing route path via array throw error

I Angular 6 application, I am passing angular routes from service class in format

{ text: string, path: string }

so the idea is I add routes dynamically, which works fine if I provide data statically, however if I replace same structure as providing data via array, it throw error,

I strongly believe is related to array structure, the way need to pass it to router.config.unshift. The unshift method accept array of Router where I am passing array of any.......

error

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

TypeError: Cannot read property 'split' of undefined at defaultUrlMatcher (router.js:530)

route service

 @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}
  ];
 }
}

app component

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}
);*/

Upvotes: 0

Views: 259

Answers (1)

Chris Tapay
Chris Tapay

Reputation: 1023

Try destructuring assignment:

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

Upvotes: 1

Related Questions