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

Angular 2调用REST API报错:无法找到模块'./data.service'

解决Angular中"Cannot find module './data.service'"错误

问题描述

我在使用Angular开发REST API服务时遇到了如下错误:

Cannot find module './data.service'

对应的服务代码如下:

import { Injectable } from '@angular/core';
import { DataService } from './data.service';
import {Http} from '@angular/http';
@Injectable()
export class GithubFollowersService extends DataService{
  constructor(http: Http) {
    super('https://api.github.com/users/mosh-hamedani/followers', http);
  }
}

解决方案

这个错误本质是Angular无法定位你导入的DataService文件,下面是几个快速排查和解决的方向:

  • 核对文件路径是否准确
    你用的相对路径./data.service要求data.service.ts必须和当前的服务文件(比如github-followers.service.ts)处于同一目录。如果DataService在其他位置,要调整路径:

    • 若在子目录:./子文件夹名/data.service
    • 若在上一级目录:../data.service
  • 检查文件名的拼写和大小写
    很多时候是大小写不匹配导致的!比如你导入的是./data.service,但实际文件名是DataService.ts或者data-service.ts,系统就会找不到。要保证导入路径和文件名的拼写、大小写完全一致(Linux/macOS环境下文件名大小写是严格区分的)。

  • 确认data.service.ts文件确实存在
    去对应的目录里检查,是不是不小心删除了这个文件,或者还没创建?如果还没写DataService的基础代码,你需要先创建它,示例代码如下:

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    
    @Injectable()
    export class DataService {
      constructor(private url: string, private http: Http) {}
    
      // 这里可以添加DataService的核心方法,比如GET请求
      get() {
        return this.http.get(this.url);
      }
    }
    
  • 重启Angular开发服务器
    偶尔Angular的文件监听会出现延迟,尤其是刚创建新文件后,重启ng serve能让系统重新扫描并识别到新的文件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:14:07