在我的 Vue.ts
(带有 TypeScript 的 Vue.js)中,我在一个文件(http 声明)中定义了一个常量 serverUrl
并将其导入到类 AuthService
的其他文件。但是这个常量在 AuthService
的属性声明或构造函数中是 UNDEFINED
。在 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();
最佳答案
如评论中所述,变量 serverUrl
未正确注入(inject)文件 AuthService
,因为这两个文件之间存在循环依赖 (从问题中提供的代码中看不到)。
解决方案是消除这两个文件之间的循环依赖,变量 serverUrl
将被正确导入。
关于TypeScript 导入的常量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55219317/