I am currently developing an Angular 6 application with the requirement to load dynamic routes from a database. To achieve this, I have created a service class called DynamicRoutingService which is responsible for loading both static and dynamic routes from the database and adding them in app.module.ts --> RouterModule.forRoot(RouteCollection).
Within the DynamicRoutingService class, I am retrieving data using the subscribe method. However, my issue arises when the page of the requested URL is rendered before the subscribe method receives the HTTP result, causing the application to throw an error of an invalid route.
I have attempted to use resolve and promises to address this issue but I am unsure of how exactly to implement it. This is where I need assistance.
App Route Resolver
@Injectable()
export class AppRoutingResolver implements Resolve<any>{
constructor(
private router: Router
){}
resolve(route: ActivatedRouteSnapshot): Promise<any> | boolean{
return false;
}
}
App.Component
export class AppComponent {
constructor(private routingService: DynamicRoutingService){
routingService.initializeDynamicRoutes(); // call service to reload routes
}
}
App.Routing.Module
@NgModule({
imports: [
RouterModule.forRoot(RouteCollection)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {
constructor(
private router: Router
) {
}
}
DynamicRoutingService
@Injectable({
providedIn: 'root'
})
export class DynamicRoutingService {
private dynamicRoutes: Route[] = [];
private waitToLoadRoutes: boolean = true;
private dynamicRoutesData: any;
private routeObject: any;
routeSubject: string = "survey";
static forEach: any;
constructor(
private router: Router,
private dynamicRoutesDataServices: DynamicRoutesDataServices
) { }
public initializeDynamicRoutes() {
this.loadDynamicRoutes();
}
public loadDynamicRoutes(): Route[] {
//LOADING DATA FROM DATABASE
this.dynamicRoutesDataServices.GetDynamicRoutesCollection(this.routeSubject)
.subscribe((result: any) => {
if (result) {
this.dynamicRoutesData = result
if (this.dynamicRoutesData) {
this.assembleDynamicRoutes();
}
}
});
return this.dynamicRoutes;
}
Data Service to Call HTTP Query
export class DynamicRoutesDataServices{
constructor(
private getDynamicRoutesQuery: GetDynamicRoutesQuery
){}
public GetDynamicRoutesCollection(routesSubject: string): any{
this.getDynamicRoutesQuery.initialise(routesSubject);
var result = this.getDynamicRoutesQuery.execute();
return result;
}
}
HTTP Query to Call API
@Injectable()
export class GetDynamicRoutesQuery extends BaseQuery<any>
{
private data: any;
public initialise(dynamicRouteSubject: string): void{
this.method = RequestMethod.Post;
if(dynamicRouteSubject){
this.data = {
RouteSubject: dynamicRouteSubject
}
}
this.setBody(this.data);
super.setEndPoint(`myside/GetDynamicRoutes`);
}
}