Search code examples
aurelia

How to use a function from injected class in Aurelia?


How to use a function from injected class in Aurelia? In my case, I'm calling a login() function (on the login page) and want to get the testMessage printed from Test Class. Unfortunately, I'm getting the following error in Chrome: "Uncaught TypeError: Cannot read property 'getTestMessage' of undefined".

test.js

export class Test {
    constructor() {
        this.testMessage = "test";
    }

    getTestMessage() {
        return this.testMessage;
    }
}

login.js

import {inject} from 'aurelia-framework';
import {Test} from 'test';

@inject(Test)
export class LogIn { 
  constructor(test) {
    this.test = test;
  }

  login(){
    console.log("login");
    this.test.getTestMessage();
  }
}

Solution

  • There is nothing wrong with your code. I copied it over to a test application and it worked. The issue most likely lies in the part you didn't reveal in your question: how you are calling the login method.

    <a href="#" click.delegate="login()">Login</a>
    

    In my test example, the view-model injecting test and subsequent HTML view is calling the login method using click.delegate. How are you calling the method?