0

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.

Alban Le Pape
  • 33
  • 1
  • 1
  • 7
  • 1
    If you're going to use the `declare`, take out the import statement for that file and just include it with a – Meggg Jun 09 '17 at 17:21
  • `import` is meant to be used with modules. `roadmap.js` is not a module exporting things, it's a global function. – Mark Jun 09 '17 at 17:52
  • Thanks, it helped but the roadmap won't render, due to undefined functions @Mark I'm confused: how should I handle this Js files to call the functions within, without having to rewrite it in typescript directly in the component? – Alban Le Pape Jun 09 '17 at 18:03
  • Did you @AlbanLePape did you try as @megg said. Import it using ` – Thirueswaran Rajagopalan Dec 27 '18 at 15:06

0 Answers0