4

I have javascript file from assets/js/chartrank.js

chartrank.js

function chartRank() {
    // do something
}

and call a function defined in it on rankuser component but it doesn't work.

rankuser.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import "../../assets/js/chartrank.js";
declare var jsObject: any;

@Component({
  selector: 'app-rankuser',
  templateUrl: './rankuser.component.html',
  styleUrls: ['./rankuser.component.css']
})
export class RankuserComponent implements OnInit, AfterViewInit {

  constructor() { }

  ngAfterViewInit() {
    jsObject.chartRank();
  }

  ngOnInit() {

  }
}

ERROR

ERROR ReferenceError: jsObject is not defined

Please help.

3
  • 1
    Try doing import * as jsObject from "../../assets/js/chartrank.js" Commented Mar 28, 2018 at 1:32
  • Thank you very much, but not work. Commented Mar 28, 2018 at 1:44
  • can you create a plunker for it ? Commented Mar 28, 2018 at 2:13

2 Answers 2

7

import doesn't work here because chartrank.js doesn't export anything.

The simplest way here is adding chartrank.js to .angular-cli.json's scripts array, and declare the chartRank(function name) as a global variable.

.angular-cli.json

"scripts": [
  "./assets/js/chartrank.js"
],

component or service

declare var chartRank: any;

@Component({
  ...
})
export class RankuserComponent implements OnInit, AfterViewInit {

  ...

  ngAfterViewInit() {
    chartRank();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Create a module with @Injectable decorator like this

import {Injectable} from "@angular/core";
@Injectable()
export class MyClass{

  constructor() {}

  chartRank() {
    // do something
   }
}

Then in component

import { Component, OnInit, AfterViewInit } from '@angular/core';
import {MyClass} from "..myClass"
declare var jsObject: any;

@Component({
  selector: 'app-rankuser',
  templateUrl: './rankuser.component.html',
  styleUrls: ['./rankuser.component.css']
})
export class RankuserComponent implements OnInit, AfterViewInit {

  constructor(private mc:MyClass) { }

  ngAfterViewInit() {
    mc.chartRank();
  }

  ngOnInit() {

  }
}

Comments

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.