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.

4
  • 1
    If you're going to use the declare, take out the import statement for that file and just include it with a <script> tag on the index Commented Jun 9, 2017 at 17:21
  • import is meant to be used with modules. roadmap.js is not a module exporting things, it's a global function. Commented Jun 9, 2017 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? Commented Jun 9, 2017 at 18:03
  • Did you @AlbanLePape did you try as @megg said. Import it using <script> in your index.html check if the roadmap.js has loaded by invoking parse in the browser console. Commented Dec 27, 2018 at 15:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.