Prasanjit
Prasanjit

Reputation: 21

Problem when loading routes from DB dynamically in angular 2

please help with a problem I have. I'm loading routes from a DB through a web service and everything work as expected when using links to those routes. But when I refresh the page or I write directly the url in the adress bar the route does not work, why?

on refresh browser, i am getting URL not found issue

Please help me on this issue.

  1. I tried to comment our base href='/' in index.html so that it will not redirect to root
  2. i tried to hold control till api response using async/await so that routecollection created first then controll will move forward for navigation

but unable to fix this issue.

i have added my code in the "app.component.ts" constructor. I call a function that loads the routes

   async getdynamicroutes1(){
  const config = this.router.config;
   await this.rest.fetchinpromise('Religious/GetRoutesCollection').then(data => {
        var indexData = data;
        indexData.forEach(element => {
          let url : string = `${element.EName.toLowerCase()}/:id`;
          config.push({path: url, component: ChaptersComponent, runGuardsAndResolvers:"always"});

          element.ReligiousBooks.forEach(religiousbook => {
            religiousbook.Chapters.forEach(chapter => {
              url = `${element.EName.toLowerCase()}/${this.removeSpace(religiousbook.EName)}/${this.removeSpace(chapter.EName)}/:id`;
              config.push({path:url, component: HomeDetailsComponent, runGuardsAndResolvers:"always"});
            });
          })
      });
      config.push({ path: "app/pagenotfound", component: PagenotfoundComponent })
      config.push({ path: "**", redirectTo: "app/pagenotfound", pathMatch: "full" } )
      this.router.resetConfig(config);
    },
    error => {
      console.log("Error :: " + error);
    });

}

on refresh browser, same page should load successfully.

Upvotes: 0

Views: 863

Answers (1)

Antoniossss
Antoniossss

Reputation: 32535

But when I refresh the page or I write directly the url in the adress bar the route does not work, why?

There are no additional routes in your application yet. You would have to try to load them on boot time before application is fully started.

You can try to use APP_INITIALIZER (https://hackernoon.com/hook-into-angular-initialization-process-add41a6b7e) or you will have to expose public variable before angular script loads the application, and append required enties directly in routing configuration.

Upvotes: 1

Related Questions