user1491987
user1491987

Reputation: 751

Angular route service with WARNING in Circular dependency

I'm trying to write a route service in my angular 6 application which can be used by any components to search for routes in my app.

The structure looks like below

home.component.ts

route.service.ts

routes.ts

app.module.ts

//routes.ts
import { HomeComponent } from './home.component.ts'
export const routes: Routes = [
  { path: 'home', component: HomeComponent }
  { path: '', component: OtherComponent }
]

//route.service.ts
import { routes } from './routes'    
@Injectable({
  providedIn: 'root'
})
export class RouteService {    
  ....
  getRouteByTerm(term: string) {
    this.routes.filter( r => {r.name.includes(term)});
  }
}

//home.component.ts
//Uses RouteService
import { RouteService } from './route.service'
...
constructor(public routeSearchService: RouteSearchService) {
    this.routeSearchService.getRouteByTerm('home');
} 
...

So since route service imports routes constant, routes imports HomeComponent, and now my HomeComponents uses route service, I'm getting a

WARNING in Circular dependency detected

How can I fix it and is there a better way of doing it?

Thanks

Upvotes: 0

Views: 428

Answers (1)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92417

I think you can use approach for "named" routes. Create separate class Url which contains map name => path and use that Url class in your export const routes: Routes = [...] array, and in RouteService.getRouteByTerm method (and remove this.routes from RouteService class).

Here is link with details.

Upvotes: 0

Related Questions