1

I've Constants.js file with below variables defined.

var baseApiUrl = "/api";
var ConstantAPI = {
  employee: baseApiUrl + "/employee",
  }

and I'm accessing using ConstantAPI.employee

I've Constants.ts as well. How can I access baseApiUrl in .ts file.

I'm trying like below

export class DataService {

constructor(@Inject(HttpClient) private http: HttpClient) {
    }

getEmployess(): Observable<any> {
        var url = ConstantAPI.employee;  // Error: Cannot find name 'ConstantAPI'
        return this.http.post(url, searchData, options)
    }
}
ethane
  • 2,329
  • 3
  • 22
  • 33
Prasad Kanaparthi
  • 6,423
  • 4
  • 35
  • 62
  • I couldn't see the import statement for ConstantAPI – Bhojendra Rauniyar Mar 23 '19 at 15:42
  • You can't import it because it's not a module. You have to add it the Angular config file as an external JS file, and then define it as a global type in Typescript. – Reactgular Mar 23 '19 at 15:56
  • 1
    Possible duplicate of [How to use external JS files in Angular 6](https://stackoverflow.com/questions/50842115/how-to-use-external-js-files-in-angular-6) – Reactgular Mar 23 '19 at 15:57
  • Why you are not declare global variable in environment.ts file . So you no need to create `constant.js` file – Bhagwat Tupe Mar 23 '19 at 18:47

1 Answers1

4

I think what you want is to reformat your JavaScript file to be exportable via module.exports like so:

module.exports.baseApiUrl = "/api";
module.exports.ConstantAPI = {
    employee: baseApiUrl + "/employee"
}

and then import like: import * as Constants from "/path/to/Constants"
or import {baseApiUrl} from "/path/to/Constants" to use them individually.

and then use like Constants.baseApiUrl
or baseApiUrl if the second way.

chennighan
  • 456
  • 3
  • 11