Calling function expression from external Javascript file within Angular4 component

左心房为你撑大大i 提交于 2020-01-17 05:22:26

问题


I'm having hard times trying to call a function expression from an external Javascript file (called roadmap.js) within the web application I'm developping using Angular4 and angular-cli. Roadmap.js is based on d3.js and available on a public Github repo.

For now, I have:

  1. Installed d3 and @types/d3 via npm
  2. Put roadmap.js file in my asset folder, after tweaking it to isolate a parse function
  3. Imported d3 in roadmap.component.ts
  4. Declared parse, the function I'd like to call in my component, as an any var in top the ts file
  5. Call the function within ngOnInit()

roadmap.component.ts

declare var parse: any;

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../../services/data/data.service';
import * as d3 from 'd3';
import '../../../../assets/js/roadmap.js';
@Component({
  selector: 'roadmap',
  templateUrl: './roadmap.component.html'
})

export class RoadmapComponent implements OnInit {
    constructor(private dataService: DataService){}
    ngOnInit() {
        new parse(); // Here is the function I'd like to call. It's defined 
                     // in roadmap.js file
    }
}

roadmap.js

// Code before this
var parse = function() {
    // Tasks
    var colors = d3.scale.category20();
    // More code 
};
// Code after this

I'm not receiving errors from the compiler but in my browser console I can read that the function parse is undefined --> Error: Uncaught (in promise): ReferenceError: parse is not defined ReferenceError: parse is not defined

So What did I miss? N.B: my modified version of roadmap.js was working on a classic html/js website, so the problem shouldn't come from that js file.

来源:https://stackoverflow.com/questions/44463368/calling-function-expression-from-external-javascript-file-within-angular4-compon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!