1

我是 Angular 的新手,刚刚尝试为google maps autocomplete创建我的第一个指令。但是我在directive.ts 文件中遇到了问题。在顶部,我有一个找不到的要求,因此无法构建应用程序。

const google = require('@types/googlemaps');

错误消息说

src/app/_directives/google-places.directive.ts(2,16) 中的错误:错误 TS2580:找不到名称“需要”。您需要为节点安装类型定义吗?尝试npm i @types/node然后添加node到 tsconfig.xml 中的类型字段。

所以我查看了我的 package.json 文件中的“@types/node”,我看到了。

   "devDependencies": {
"@angular-devkit/build-angular": "~0.13.0",
"@angular/cli": "~7.3.9",
"@angular/compiler-cli": "~7.2.0",
"@angular/language-service": "~7.2.0",
"@fortawesome/fontawesome-pro": "^5.9.0",
"@types/jasmine": "~2.8.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "~4.5.0",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~1.1.2",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.11.0",
"typescript": "~3.2.2"
}

然后我查看了 tsconfig.json 的类型,没有看到,所以我添加了它。

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "types": [
      "node"
    ]
  }
}

然后我进行了重建,但仍然找不到“要求”,因此构建失败。

只是为了获得更多信息,这里是指令文件。Intellisense 建议我将“要求”转换为导入,所以我这样做了,但这似乎也没有解决它。

import {
  Directive,
  OnInit,
  ElementRef
} from '@angular/core';
const google = require('@types/googlemaps'); // error here with require
// import google = require('@types/googlemaps'); // doesn't work either

@Directive({
  selector: '[appGooglePlaces]'
})

export class GooglePlacesDirective implements OnInit {
  private element: HTMLInputElement;

  constructor(private elRef: ElementRef) {
    // elRef will get a reference to the element where
    // the directive is placed
    this.element = elRef.nativeElement;
  }

  ngOnInit() {
    const autocomplete = new google.maps.places.Autocomplete(this.element);
  }

}

4

1 回答 1

0

这是我为弄清楚它所做的。去开发者 github 页面查看他的文件。(与他的导游所说的不同)

A. 他没有像他在指南中所做的那样导入@types/googlemaps B. 在指令的顶部有这个 ///

于 2019-07-15T05:33:47.143 回答