Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

How to read constants in .js file from .ts file

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)
    }
}

Upvotes: 1

Views: 2224

Answers (1)

chennighan
chennighan

Reputation: 476

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.

Upvotes: 5

Related Questions