【问题标题】:Cannot find namespace 'ng'找不到命名空间“ng”
【发布时间】:2017-08-13 18:36:51
【问题描述】:

我正在将简单的 Angular 1.6 项目重写为打字稿。我已经声明了类型依赖项,它们被编译和安装。尽管在我的服务中存在编译错误“找不到命名空间'ng'”。 Angular 名称也无法识别。

Screenshot

tsconfig.json

{
    "files": [
        "app/**/*.ts",
        "app/**/*.js",
        "main.js",
        "renderer.js"
    ],
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "declaration": false,
        "noImplicitAny": false,
        "allowJs": false,
        "rootDir": ".",
        "typeRoots": ["./typings"] 
    }
}

typings.json

{
  "dependencies": {
    "angular": "registry:dt/angular#1.6.0+20170321201455"
  },
  "globalDependencies": {
    "jquery": "registry:dt/jquery#1.10.0+20170310222111"
  }
}

service.ts

module Services {

    export interface IMyService {
    }

    export class MyService {

        http: ng.IHttpService;
        location: ng.ILocationService;

        constructor($http: ng.IHttpService, $location: ng.ILocationService) {
            this.http = $http;
            this.location = $location;
        }

    }
}

【问题讨论】:

    标签: javascript angularjs typescript visual-studio-code electron


    【解决方案1】:

    也许您应该将angular 类型添加到tsconfig.json,如下所示:

    {
        ...
        "compilerOptions":
            ...
            "types": [
                "angular"
            ],
    }
    

    如果这不起作用,因为 typings 已被弃用,我建议您使用 npm 安装 @types/angular

    npm install --save-dev @types/angular

    并像上面一样包含它。

    干杯。

    【讨论】:

    • >npm install --save @types/angular and import angular = require("@types/angular");已解决问题,谢谢。
    【解决方案2】:

    在下面添加package npm

    npm install --save-dev @types/angular

    然后在 .ts 文件顶部包含以下行:

    import * as angular from "angular".

    它将解决错误。谢谢。

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 2012-07-14
      • 2011-03-10
      • 2019-08-31
      • 1970-01-01
      相关资源
      最近更新 更多