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())
}
1
  • A similar question was just posted (with a valid answer): stackoverflow.com/a/67634652/6513921. And this is the first result I get when I googled "use js function in angular". Commented May 21, 2021 at 11:00

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Yes my bad I meant in the same file of the component but before the class declaration, I just edited my original answer
Thanks it works, I actually had written the path wrong so it was my fault

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.