TypeScript 导入的常量未定义

Ond*_*sky 11 typescript

在我的 Vue.ts(带有 TypeScript 的 Vue.js)中,我serverUrl在一个文件(http 声明)中定义了一个常量,我将它导入到另一个文件中,并带有 class AuthService。但是这个常量UNDEFINED在 的属性声明或构造函数中AuthService。在login()函数中没问题。有什么问题?这是我的文件。网址:

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'   } });
Run Code Online (Sandbox Code Playgroud)

和 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();
Run Code Online (Sandbox Code Playgroud)

Sté*_*azi 13

正如评论中所讨论的,该变量serverUrl未正确注入文件中,AuthService因为这两个文件之间存在循环依赖关系(从问题中提供的代码中不可见)

解决方法是去除这两个文件之间的循环依赖,变量serverUrl将被正确导入。