1

I am using AngularJS and Typescript. The problem I am trying to solve is the following:

  • In the Typescript controller class I have an array of loans, each loan with a currency object.
  • In the UI I have one tab per currency.

I want to call a getLoans() method to show the loan list within each tab (currency). In the class, I have an array with all the loans and the getLoans() method filters that array based on the selected tab (selected currency) and returns the loans filtered.

Below is the code:

class MyClass {
    public selectedCurrency: app.models.Currency;
    private loans: app.models.Loan[];

    getLoans(): app.models.Loan[] {
        if (this.loans) {
            return this.loans.filter(this.filterBySelectedCurrency);
        }
        return null;
    }

    filterBySelectedCurrency(loan: app.models.Loan): boolean {
        return loan && this.selectedCurrency && loan.Currency == this.selectedCurrency;
    }
}

The above code is not working because in the filterBySelectedCurrency(..) method this.selectedCurrency is undefined. However, debugging the code I see that before calling it (within the getLoans() method), this.selectedCurrency has the correct value.

Apparently for some reason, I can't access the class variable this.selectedCurrency from within the filter method. Is this the case?

Thanks in advance!

1 Answer 1

2

Passing in the function directly will cause the context—this—to be lost. You can maintain the context by passing in an arrow function instead.

Change this:

return this.loans.filter(this.filterBySelectedCurrency);

To this:

return this.loans.filter((loan) => this.filterBySelectedCurrency(loan));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.