0

I've got a component where I'm trying to define a function that reads through the following js file and checks if a certain string value is contained in it. How can I do it? It's path is '../../../assets/beacons.js' (from my component) and it's named beacons.js

const allBeacons = {
    "RIPE": [
        "84.205.64.0/24",
        "84.205.65.0/24",
        "84.205.67.0/24",
        "84.205.68.0/24",
        "84.205.69.0/24",
        "84.205.70.0/24",
        "84.205.71.0/24",
        "84.205.74.0/24",
        "84.205.75.0/24",
        "84.205.76.0/24",
        "84.205.77.0/24",
        "84.205.78.0/24",
        "84.205.79.0/24",
        "84.205.73.0/24",
        "84.205.82.0/24",
        "93.175.149.0/24",
        "93.175.151.0/24",
        "93.175.153.0/24"].map(i => i.toLowerCase()),
    "rfd.rg.net": [
        "45.132.188.0/24",
        "45.132.189.0/24",
        "45.132.190.0/24",
        "45.132.191.0/24",
        "147.28.32.0/24",
        "147.28.33.0/24",
        "147.28.34.0/24",
        "147.28.35.0/24",
        "147.28.36.0/24",
        "147.28.37.0/24",
        "147.28.38.0/24",
        "147.28.39.0/24",
        "147.28.40.0/24",
        "147.28.41.0/24",
        "147.28.42.0/24",
        "147.28.43.0/24",
        "147.28.44.0/24",
        "147.28.45.0/24",
        "147.28.46.0/24",
        "147.28.47.0/24"].map(i => i.toLowerCase())
}
Maurizio Brini
  • 216
  • 1
  • 12
  • A similar question was just posted (with a valid answer): https://stackoverflow.com/a/67634652/6513921. And [this](https://stackoverflow.com/q/49526681/6513921) is the first result I get when I googled "use js function in angular". – ruth May 21 '21 at 11:00

1 Answers1

1

You need to include the js file in the bundle by telling angular about it:

  1. Open angular.json, and add the path to the "scripts" array:
"scripts": ["src/assets/beacons.js"]
  1. In the top of your component file (before class declaration) declare the variable as global so typescript won't complain about it (the name must match to the one in the js file):
  type Beacons = {/* Define type if you want */} | any
  declare const allBeacons: Beacons 
  1. Now you can use it as a global variable in your app:
ngOnInit() {
  console.log(allBeacons)
}
Two Horses
  • 1,401
  • 3
  • 14
  • 35
  • It's not working, the console.log says: "allBeacons is not define". I've followed the steps you suggested. I had to place `declare const allBeacons: Beacons` before the component or I would get `A class member cannot have the 'const' keyword`. – Maurizio Brini May 21 '21 at 13:06
  • Yes my bad I meant in the same file of the component but before the class declaration, I just edited my original answer – Two Horses May 21 '21 at 13:11
  • Thanks it works, I actually had written the path wrong so it was my fault – Maurizio Brini May 21 '21 at 13:14