I'm working on an angular 7 application, where I have been facing an interesting issue right now.
My aim is to not using the "hardcoded URLs" throughout in the application.
So, I have an approach like maintaining a single config file where I can have all the site URLs and supplying to the needed components and modules.
Having a configuration like below codes.
routes.ts // Url Configuration File
import { LayoutComponent } from './layout/layout.component';
import { AdminIndexComponent } from './admin-index/admin-index.component';
import { AdminRegisterComponent } from './admin-register/admin-register.component';
import { LoginComponent } from './login.component';
export class AppRoutes {
// Angular components url
public static componentsUrl = {
base: {
path: '',
component: AdminIndexComponent,
pathMatch: 'full'
},
register: {
path: 'register',
component: AdminRegisterComponent
},
login: {
path: 'login',
component: LoginComponent
},
home: {
path: 'home',
component: LayoutComponent
}
};
routes-service.ts
import { Injectable } from '@angular/core';
import { AppRoutes } from './routes';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root',
})
export class AppRouterService {
routesArray = [];
getAppRoutesArray() {
Object.entries(AppRoutes.componentsUrl).forEach(
([key, value]) => this.routesArray.push(value)
);
return this.routesArray;
}
}
app-routing.module
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppRouterService } from './routes-service';
const routes: Routes = ;
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Everything is good at this level. I can able to supply the URL for the routing.
But the interesting case is, I have another component that needs the URL.
admin-index.component.ts
import { Component, OnInit } from '@angular/core';
import { RegistrationModule } from 'shared-components';
import { AppRouterService } from '../routes-service'; // Causing the circular dependency
@Component({
selector: 'app-admin-index',
templateUrl: './admin-index.component.html',
styleUrls: ['./admin-index.component.scss']
})
export class AdminIndexComponent implements OnInit {
appRoutesUrl;
constructor(private regModule: RegistrationModule, private routerService: AppRouterService) { }
ngOnInit() {
this.appRoutesUrl = this.routerService.getAppRoutesObject(); // This variable in binding to component html. So I can retrieve the url from config file
}
}
While I'm doing like this I have got a warning like "WARNING in Circular dependency detected". I know the import of "AdminIndexComponent" on routes.ts is causing this warning.
May I know how to get rid of this issue? Also please suggest an efficient way to do this?
Thank you.
First in app.module.ts, add
Then add this imports,
After that you can create route like as follows in the same file.