Search code examples
angulardexie

Dexie - Check if a record exists and initialize it if not present


I'm implementing Dexie 2.0 in an Angular2 project.

I have a simple table that should contain only one record use for order naming.

What I have to do is check in IndexedDb if the table has the record and if not, initialize it... Very simple.

This is the code:

this.OrderCounter.toArray().then(function (arr) {
        if (arr.length == 1) {
          console.log('Do nothing');
        }
        else {
          console.log('Initialize Counter');          
          this.OrderCounter.add(1);          
        }
      });

In this moment the table is empty and if I run the script I get "this is undefined" on the row command that initialize the record...

What do I have to change?

Thanks to support


Solution

  • It's the nature of this in javascript that is the problem. Try replace function (arr) { ... } with an arrow function (arr) => { ... } and your this pointer will stick to your class instance.