Encountering an Issue with Angular Routing
I'm relatively new to Angular and making good progress. I want Angular's routing functions to be dynamic so I created a small api for Angular to fetch from, returning an array. However, when I iterate over the array, the contents are not being applied when loading them into the Routing Module. Strangely, if I use the same method to load hardcoded routes, it works perfectly!
When I try to access urls like cms/bla or cms/dashboard, everything works fine. But any other url is not recognized. The value of [i]['path'] in the array is definitely a string. For example, one of the strings is 'cms/login' but Angular returns it as not found. Am I overlooking something crucial here?
Upon reviewing the console, it displays: (3) [{...}, {...}, {...}]. When I inspect its contents, all my routes are present including the hardcodes ones at the very bottom.
Snippet of My Code
import { ApiResult } from './objects/api';
import { DashboardComponent } from './dashboard/dashboard.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes, } from '@angular/router';
import { environment } from '../environments/environment';
const routes: Routes = prepareRoutes();
function prepareRoutes() {
const newRoutes: Routes = [{path: 'cms/bla', component: DashboardComponent}];
newRoutes.unshift({path: 'bla', component : DashboardComponent});
newRoutes.unshift({path: 'cms/dashboard', component : DashboardComponent});
fetch(environment.apiUrl + '/routes/').then((value: Response) => {
return value.json();
}).then((routeResults: ApiResult) => {
for (let i = 0; i < routeResults.data.length; i++) {
newRoutes.unshift({path: routeResults.data[i]['path'], component: DashboardComponent});
}
});
return newRoutes;
}
console.log(routes);
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {
}
UPDATE #1
import { ApiResult } from './objects/api';
import { DashboardComponent } from './dashboard/dashboard.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes, Router} from '@angular/router';
import { environment } from '../environments/environment';
const routes: Routes = [{path: 'cms/bla', component: DashboardComponent},
{path: 'bla', component : DashboardComponent},
{path: 'cms/dashboard', component : DashboardComponent}];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {
constructor(router: Router) {
fetch(environment.apiUrl + '/routes/').then((value: Response) => {
return value.json();
}).then((routeResults: ApiResult) => {
for (let i = 0; i < routeResults.data.length; i++) {
router.config.unshift({path: routeResults.data[i]['path'], component: DashboardComponent});
}
console.log(router.config);
});
}
}