Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript imported constant is undefined

Tags:

typescript

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();
like image 751
Ondrej Vencovsky Avatar asked Mar 18 '19 10:03

Ondrej Vencovsky


People also ask

How do I import files into TypeScript?

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 .

What is declare module in TypeScript?

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

What is export default in TypeScript?

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.


1 Answers

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.

like image 151
Stéphane Eintrazi Avatar answered Sep 28 '22 04:09

Stéphane Eintrazi