首页 > 解决方案 > 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'   } });

和 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();

标签: typescript

解决方案


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

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


推荐阅读