Angular路由resolve中如何在单个方法注入多个服务?
在Angular路由Resolve方法中注入多个服务
你不需要把多个服务作为参数传给inject(),正确的做法是在单个resolve回调里多次调用inject()函数,分别获取每个需要的服务实例。
修改后的代码示例:
{ path: ':id', component: RecipeDetailComponent, resolve: { detail: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => inject(RecipeService).getRecipes()[route.params['id']], data: () => { // 分别调用inject获取两个服务 const httpService = inject(HttpService); const recipeService = inject(RecipeService); // 这里可以结合两个服务的逻辑编写业务代码 return httpService.fetchRecipes().pipe( // 示例:将获取到的食谱数据同步到RecipeService中 tap(fetchedRecipes => recipeService.updateRecipes(fetchedRecipes)) ); } } }
关键说明:
inject()函数的设计是每次调用解析一个依赖,不能一次性传入多个服务类型参数- 在同一个注入上下文(比如当前的resolve回调函数)中,多次调用
inject()是完全合法的,Angular会自动处理依赖解析 - 先将服务实例存入变量,后续就可以在回调里自由组合两个服务的逻辑
内容的提问来源于stack exchange,提问作者Issac Howard
相关产品推荐
相关产品推荐

