You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Aurelia中如何调用注入类的函数?登录场景报错求助

解决"Aurelia中调用Test类方法时出现TypeError: Cannot read property 'getTestMessage' of undefined"的问题

Hey there, let's figure out this TypeError you're hitting when trying to call getTestMessage() from your Test class in the login function. That error means you're trying to invoke the method on an undefined value—in other words, your Test instance doesn't exist when you try to use it.

First, let's break down the issue: your test.js code is totally valid (it exports a class with a properly initialized testMessage and getter method). The problem lies in how you're importing and using the Test class in your incomplete login.js file.


解决方案1:使用Aurelia的依赖注入(推荐)

Since you're already using Aurelia's inject utility, let's fix the login class to properly inject and use the Test instance:

// login.js
import {inject} from 'aurelia-framework';
import {Test} from './test'; // 确保路径正确,若test.js和login.js同目录则用./test

@inject(Test) // 告诉Aurelia注入Test类的实例
export class Login {
  // 接收注入的Test实例并绑定到类属性
  constructor(testInstance) {
    this.test = testInstance;
  }

  login() {
    // 此时this.test是有效的Test实例,调用方法不会报错
    const testMsg = this.test.getTestMessage();
    console.log(testMsg); // 会输出"test"
  }
}

解决方案2:手动实例化Test类(若无需依赖注入)

If you don't need Aurelia's dependency injection for this class, you can simply create a new instance directly in your login function:

// login.js
import {Test} from './test'; // 同样要确保导入路径正确

export class Login {
  login() {
    // 手动创建Test类的实例
    const testInstance = new Test();
    const testMsg = testInstance.getTestMessage();
    console.log(testMsg); // 输出"test"
  }
}

常见错误排查点

  • 导入路径错误: 仔细检查import {Test} from '...'的路径,如果test.js和login.js在同一文件夹,必须写./test,不能用不完整的路径比如'te...'。
  • 缺少实例化/注入: 如果你忘记注入或手动创建Test实例,任何对它的引用都会是undefined,从而抛出这个TypeError。
  • this上下文丢失: 如果login()方法被用作回调(比如按钮点击事件),要确保this指向Login类的实例,可以用箭头函数或.bind(this)来修复。

内容的提问来源于stack exchange,提问作者George P.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:38:53