You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17 ResolveFn调用服务方法报错:loadById不是函数

Angular 17 ResolveFn 报错:Inject(...).loadById is not a function 解决方案

问题根源是你在函数式Resolver中错误使用了Inject装饰器获取服务实例,Angular函数式依赖注入需要使用inject()函数。

修改后的Resolver代码

import { of } from 'rxjs';
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { Livro } from '../models/livro';
import { LivrosService } from '../services/livros.service';

export const livrosResolver: ResolveFn<Livro> = (route, state) => {
  // 使用inject函数获取LivrosService实例
  const livrosService = inject(LivrosService);

  if(route.params?.['id']){
    // 路由参数为字符串,转换为number类型匹配服务方法参数
    return livrosService.loadById(Number(route.params['id']));
  }

  return of({_id: Number(null), name: '', desc: ''});
};

关键说明

  1. 依赖注入方式错误:Inject是类/构造函数参数的装饰器,不能直接在函数中调用获取服务实例;inject()是Angular专为函数式场景(如ResolveFn、CanActivateFn等)提供的依赖注入函数。
  2. 参数类型转换:路由参数route.params的值默认是字符串,而LivrosService.loadById接收的是number类型,必须转换类型避免HTTP请求路径错误。

你的LivrosService实现和路由配置没有问题,修改Resolver后即可正常运行。

内容的提问来源于stack exchange,提问作者Drakonor Arckhnarus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:53:11