【问题标题】:Angular route service with WARNING in Circular dependency循环依赖中带有警告的角度路由服务
【发布时间】:2018-11-09 19:29:11
【问题描述】:

我正在尝试在我的 Angular 6 应用程序中编写一个路由服务,任何组件都可以使用它来搜索我的应用程序中的路由。

结构如下图

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');
} 
...

所以由于路由服务导入路由常量,路由导入 HomeComponent,现在我的 HomeComponents 使用路由服务,我得到了一个

检测到循环依赖中的警告

我该如何解决?有没有更好的方法?

谢谢

【问题讨论】:

    标签: angular typescript routes circular-dependency


    【解决方案1】:

    我认为您可以对“命名”路线使用方法。创建单独的 class Url 包含地图名称 => 路径,并在 export const routes: Routes = [...] 数组和 RouteService.getRouteByTerm 方法中使用该 Url 类(并从 RouteService 类中删除 this.routes)。

    这里是link with details.

    【讨论】:

    • 我将方法更改为静态方法,并删除了@Injectable,将服务从 homecomponent 构造函数中取出,所以现在它变成了 RouterService.getRouteByTerm('') 但我仍然看到循环警告。
    • @user1491987 所以尝试第二种方法 - 将该函数移动到单独的静态类 RouteHelper
    • 我添加了一个静态类,如下所示,但我仍然收到同样的警告,如果我做对了,请告诉我:export class RouteService{ static Search = class { static getRouteByTerm(term: string ) { routes.filter( r=> { (r.name || r.path).includes(term) }); } }; }
    • @user1491987 我更新我的答案(并完全改变它)
    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2017-08-17
    • 2021-08-15
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多