In my Vue.ts (Vue.js with TypeScript) I have defined a constant serverUrl
in one file (http declaration) and I'm importing it into the other file with class AuthService
. But this constant is UNDEFINED
in either property declaration or constructor of AuthService
. In the login()
function it's OK. What's the problem?
Here are my files. http:
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
export const serverUrl = 'http://localhost:63523'; // serverUrl Constant
export const http = axios.create({ timeout: 20000, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json' } });
And the AuthService:
import { http, serverUrl } from '@/services/http';
export class AuthService {
private authUrl: string = serverUrl + '/' + 'auth/login'; // serverUrl = UNDEFINED
constructor() {
this.authUrl = `${serverUrl}/auth/login`; // serverUrl = UNDEFINED
}
public login(login: string, password: string ) {
const authUrl2: string = serverUrl + '/' + 'auth/login'; // serverUrl = OK!
return http.post(authUrl2, {login, password});
}
}
export const authService = new AuthService();
To import a class from another file in TypeScript: Export the class from file A , e.g. export class Employee {} . Import the class in file B as import { Employee } from './another-file' . Use the class in file B .
In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).
For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.
As discussed in the comments the variable serverUrl
was not correctly injected in the file AuthService
because there was a circular dependency between theses two files (not visible from the code provided in the question).
The solution is to remove the circular dependency between theses two files and the variable serverUrl
will be correctly imported.
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