This is how I import app.config.ts class in typescript and use it. How do I import the same AppConfig
class in Javascript file (config.js) and access the method getConfig
?
service.ts
import { AppConfig } from '../app.config';
constructor(private http: Http, private config: AppConfig) {
this.dataURL = this.config.getConfig('restApi') + '/api/getdata/'
console.log(this.dataURL)
}
Importing TypeScript files dynamically into JavaScript requires additional compilation step, which is troublesome to write for many. Popular typescript-require package seems to be obsolete and doesn't allow much customization.
To import a class from another file in JavaScript:Export the class from file A , e.g. export class Employee {} . Import the class in file B as import {Employee} from './another-file. js' . Instantiate the class in file B .
I don't know exactly what you are asking, so I've split it into to parts:
The best solution would be to rename your config.js to config.ts and treat it like a typescript file.
i.e. if you have this:
export class AppConfig {
foo: string;
bar: number;
}
And in your config.js you have this:
export const Config = {
foo: 'Hello World',
bar: 42
}
but I assume you want something akin to:
import { AppConfig } from './app.config'
export const Config: AppConfig = {
foo: 'Hello World',
bar: 42
}
Then just rename config.js to config.ts. It has to be a typescript file for type checking anyways (unless you put the allowJs rule in the tsconfig.json, but even then I don't think it's smart to import .ts files into .js files).
Importing JavaScript files dynamically doesn't actually work in the browser for a couple of technical reasons, not the least of which is security, but also because ES6's "import" (or node's "require") is not in the browser standard.
Instead, I recommend you convert your config to a JSON
file and use JavaScript's native JSON.parse
to parse it. I.E:
http.get(this.dataUrl).toPromise().then(response => {
let config = null;
try {
config = JSON.parse(response.data);
} catch (e) {
console.error("Couldn't parse response!");
}
this.config = new AppConfig(config); // See note
}
Or something along those lines.
Note: I assume you have both a copy and a default constructor for your AppConfig class. If you don't, then you can create one, create a parse-function or something akin to that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With