gpt4 book ai didi

javascript - 在 Angular 8 应用程序中使用外部 JavaScript 库

转载 作者:搜寻专家 更新时间:2023-10-30 20:58:20 26 4
gpt4 key购买 nike

我是 Angular 的新手,我想开发一个漏斗图。我喜欢funnel-graph-js图书馆。我尝试了很多但没有成功。

这是我的funnel-graph-directive.ts

import { Directive, ElementRef } from '@angular/core';

// import * as graph from '../../../assets/js/funnel-graph.js';
import * as graph from 'funnel-graph-js/dist/js/funnel-graph.js';
var graph = new FunnelGraph({
container: '.funnel',
gradientDirection: 'horizontal',
data: {
labels: ['Impressions', 'Add To Cart', 'Buy'],
subLabels: ['Direct', 'Social Media', 'Ads'],
colors: [
['#FFB178', '#FF78B1', '#FF3C8E'],
['#A0BBFF', '#EC77FF'],
['#A0F9FF', '#7795FF']
],
values: [
[3500, 2500, 6500],
[3300, 1400, 1000],
[600, 200, 130]
]
},
displayPercent: true,
direction: 'horizontal'
});

graph.draw();
@Directive({
selector: '[appFunnelGraph]'
})
export class FunnelGraphDirective {
style: any;
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}

我在我的 angular.json 中添加了这些行

"styles": [
"src/styles.scss",
"./node_modules/funnel-graph-js/dist/css/main.css",
"./node_modules/funnel-graph-js/dist/css/theme.css"
],
"scripts": [
"./node_modules/funnel-graph-js/dist/js/funnel-graph.js"
]

这是我得到的错误 enter image description here

最佳答案

只要您在 html 中链接 javascript 文件,它就可以正常工作。

编辑:

包含附加 javascript 文件的更好方法是将其放入 angular.json 文件的“脚本”部分。您还可以添加

declare const FunnelGraph: any

为了编译无误。这取自 an answer to a stackoverflow questionthis guide .记住也要在该 json 中包含 css 文件!

编辑结束

您收到该错误是因为代码试图查找具有名为“funnel”的类的 HTML 元素,但找不到它。既然是指令,再泛化一点就更好了。

首先,您应该将图形生成代码移到构造函数中,因为那是指令逻辑所在的位置。为了更好地概括此指令,最好为该元素提供一个唯一的 id 并相应地更改代码。我会这样做:

HTML:

<div id="funnel-graph-1" appFunnelGraph></div>

JS:

import { Directive, ElementRef } from '@angular/core';

// It should be fine to just import this in the html with a script tag
// import * as graph from 'funnel-graph-js/dist/js/funnel-graph.js';

@Directive({
selector: '[appFunnelGraph]'
})
export class FunnelGraphDirective {
style: any;
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';

var graph = new FunnelGraph({
// Generalize the container selector with the element id
container: '#' + el.nativeElement.id,
gradientDirection: 'horizontal',
data: {
labels: ['Impressions', 'Add To Cart', 'Buy'],
subLabels: ['Direct', 'Social Media', 'Ads'],
colors: [
['#FFB178', '#FF78B1', '#FF3C8E'],
['#A0BBFF', '#EC77FF'],
['#A0F9FF', '#7795FF']
],
values: [
[3500, 2500, 6500],
[3300, 1400, 1000],
[600, 200, 130]
]
},
displayPercent: true,
direction: 'horizontal'
});

graph.draw();
}
}

关于javascript - 在 Angular 8 应用程序中使用外部 JavaScript 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58166597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com