Angular5:Dygraph 未在运行时定义

Angular5: Dygraph is not defined in runtime

使用 Angular 5 结合 dygraphs 库,在运行时我收到错误:'Dygraph is not defined',尽管安装了 dygraphs 库。

component.ts 文件:

import { Component, AfterViewInit } from '@angular/core';

declare var Dygraph: any;

@Component({
...
})
export class MyComponent implements AfterViewInit {

  constructor() {
  }

  ngAfterViewInit() {
      let div = document.getElementById('divId');
      new Dygraph(div, "Time,Value\n", {});
  }
}

component.html 文件:

<div id="divId"></div>

package.json 文件:

 "dependencies": {
    ...
    "dygraphs": "^2.1.0",
  },

是否可以使用 Angular2+ 的纯 dygraphs?有 ng-dygraphs 库,但我想使用纯 dygraphs。

问题是 typescript 不知道类型,您还需要从模块 dygraphs 导入您使用的 Dygraph。尝试安装打字文件:

npm install --save-dev @types/dygraphs

在你的文件中:

import Dygraph from 'dygraphs';

... 

new Dygraph(...)

虽然我觉得我破解了其中的大部分内容,但它确实得到了相关结果。网页上的三个 dygraphs 实例。我最初尝试使用 ng-dygraphs 但没有成功,所以我尝试使用 https://github.com/danvk/dygraphs-es6 处的信息以及来自 Andrei Tătar 的早期答案 here 插入没有包装的 dygraphs ].

我没有像 Q 中那样编辑 package.json 文件。没有包装器的缺失部分是添加类型(已经添加了 dygraphs 和 ng-dygraph 并在 angular -cli 构建项目):

ng add @types\dygraphs

然后此代码有效

<div #graph></div>

使用组件详细信息(来自 的@ViewChild 魔法)

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import Dygraph from 'dygraphs';

@Component({
  selector: 'app-dygraph',
  templateUrl: './dygraph.component.html',
  styleUrls: ['./dygraph.component.css']
})
export class DygraphComponent implements OnInit {
  @ViewChild('graph')
  graphdiv: ElementRef;
  ngOnInit() {
    new Dygraph(this.graphdiv.nativeElement,
      `Date,A,B
      2016/01/01,10,20
      2016/07/01,20,10
      2016/12/31,40,30
      `, {
        fillGraph: true
    });  
  }

图表成功。所以我又回去添加 ng-graphs 了。并不断收到相同的错误,所以最终我进去编辑了

node_modules\ng-dygraphs\ng-dygraphs.es5.js

node_modules\ng-dygraphs\ng-dygraphs.js

包括行:

import Dygraph from 'dygraphs';

ng-dygraphs 然后 "found" Dygraphs 和...我也得到了三个趋势。

我的 app.component.html 文件包含三个趋势中的三个。

<app-dygraph></app-dygraph>
<app-dygraph></app-dygraph>
<app-dygraph></app-dygraph>

免责声明:我只是破解它直到它对我有用。 YMMV.

您需要将 dygraphs 和 types/dygraphs 包安装到您的 Angular 项目中

npm i dygraphs --save npm i @types/dygraphs --save 之后只需将其写在您使用 Dygraphs

的组件中
declare var Dygraph:any;

它对我有用。使用它们时它没有向我显示任何错误。我正在与 Angular 8.

一起工作