How to add listener on data change in LokiJS?

I’m trying to add listener to LokiJS such that I get notified whenever there is change in data in any of the collections (though as per documentation LokiJS supports notification of data change). However I’m unable to get notification on data change.

Below is the code snippet I’m using:

import { Component, OnInit } from '@angular/core';
import { Message } from 'primeng/components/common/api';
import { MessageService } from 'primeng/components/common/messageservice';

import * as loki from 'lokijs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  db: loki;

  constructor(private messageService: MessageService) {

  }

  ngOnInit() {
    this.db = new loki('kp-loki.db');
    this.db.addCollection('kp_users', { asyncListeners: true });
    console.log(this.db.addListener('changes', event => console.log(event)));
  }

  add() {
    this.messageService.add({ severity: 'sucess', summary: 'data added' });
    const uu = this.db.getCollection('kp_users');
    uu.insert({ id: 1, name: 'kp', city: 'blr' });
  }

  view() {
    const uu = this.db.getCollection('kp_users');
    this.messageService.add({ severity: 'sucess', summary: JSON.stringify(uu.data) });
  }

}

6 thoughts on “How to add listener on data change in LokiJS?”

Leave a Comment