1

I need to use a remote cdn script inside an angular component. (It's to display a pop up for the GDPR). I already have imported the script, but i can't call the methods inside the component.

So i have imported the script in my index.html file. In my app.component.ts file, i have declared a variable for the function i want to call. But the browser is still telling me that the variable is undefined.

Index.html file :

<!doctype html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
 <meta charset="utf-8">
  <title>AutoDiagnostic</title>
  <base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
  <script src="http://cdn.tagcommander.com/3905/uat/tc_autodiag_55.js"></script>
</body>
</html>

app.component.ts file :

import { Router, NavigationEnd, Event } from '@angular/router';
import { Component, OnInit } from '@angular/core';

declare let tc_events_55: any; // <=== the function i want to use

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(private router: Router) {
    router.events.subscribe((event: Event) => {
      if (event instanceof NavigationEnd) {
        tc_events_55(this, 'virtualPageview', { page: this.router.url });
  }
});
 }
  ngOnInit(): void {}

  isTagCoCookieCreated() {
    return document.cookie.indexOf('TC_OPTOUT') !== -1;
  }
}

I expected it to make me able to use the function from the cdn .js script, but i doesn't. I can't integrate the script as a local ressource because i have to call it from cdn depending on the deploying environment.

Any Ideas ? :)

matirmv
  • 283
  • 2
  • 14
  • Possible duplicate of [Angular2: import external js file into component](https://stackoverflow.com/questions/37081943/angular2-import-external-js-file-into-component) – Akber Iqbal Feb 15 '19 at 09:33

1 Answers1

0

It's normally that it is not work. The problem is that you need to import the library in your app.module. You need to do something like this in the app.module:

import 'tc_autodiag_55';

and then you can use the library in the other component.

Doflamingo19
  • 1,591
  • 4
  • 12
  • 32