Kristjan O.
Kristjan O.

Reputation: 914

Import external JS into Angular 8

I am writing application in Angular 8 (8.0.3) and I need to import external JS file which will hold a URL reference for API that can and will change. The problem I am facing is that changes I do into this file after I have compiled Angular app (with ng build --prod), changes are not being picked up inside Angular, but it keeps the data as it was when the app was built.

This is the external JS file:

export function apiUrl() {
    return 'http://www.localhost.local/api/v1/';
}

The apiUrl() does return proper value, but if I change it, the updated value is not reflected inside Angular app.

I also created .d.ts. file:

export declare function apiUrl();

Imported the external JS file into index.html:

<script type="module" src="assets/js/api_url.js"></script>

Used it in angular service:

import {apiUrl} from '../../assets/js/api_url';
export class ApiService {

    private api_url: string = apiUrl();

    constructor(...) {
        console.log(apiUrl());
    }
}

I did NOT import this file in angular.json and even if I do, nothing changes.

So, how to create and then import an external JS file that after it changes, the Angular app does pick up it changes?

EDIT: Do note that I do not need a live app reload when this file changes, but I need for the file to be loaded from server each time the Angular app starts.

EDIT 2: To explain why I need this. The Angular app will be used on internal network to which I do not have access to. The client currently does not know the API URL and even if he would, it can change at any moment. That's the reason why I need this to work.

Upvotes: 0

Views: 854

Answers (1)

Damian Plewa
Damian Plewa

Reputation: 1193

In that case you should use environments

You can find them in src/environments directory.

For local development you have environment.ts file, for production environment.prod.ts

Example environment.ts:

export const environment = {
  production: false,
  apiUrl: 'http://www.localhost.local/api/v1/'
};

environment.prod.ts:

export const environment = {
  production: true,
  apiUrl: 'http://www.producitonurl.com/api/v1/'
};

To use this apiUrl value you need to import environment file in typescript file like this: You need to import environment.ts not any other environment file, because angular is replacing it while building application

import {environment} from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class MyApiService {
    apiUrl = environment.apiUrl;
}

But in case you want to use method from <script type="module" src="assets/js/api_url.js"></script>, just use window object like this:

private api_url: string = (window as any).apiUrl();

Upvotes: 1

Related Questions