In my project I have a service that loads data from NeDB. For this purpose I have a method getData()
. In my component, using ngOnInit()
hook I call this method.
Here's where the problem lies.
If getData()
uses promises everything works as intended and on startup of my app I have the result of query to a database loaded and displayed.
getData() using promises
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import * as Datastore from 'nedb';
import * as path from 'path';
@Injectable()
export class SearchService {
db: any;
constructor() {
this.db = new Datastore( {
filename: path.resolve('src/assets/db.json'),
autoload: true,
});
}
getData(){
return new Promise((resolve, reject) => {
this.db.find({}, (err, docs) => {
if (err) reject(err);
resolve(docs);
});
})
}
}
But if I try to do this using observables nothing is loaded and displayed (the result passed to subscriber is undefined
).
getData() using observables
getDataObs(){
return new Observable(subscriber => {
this.db.find({}, (err, docs) => {
if (err) subscriber.error(err);
subscriber.next(docs);
})
})
}
App Component
import { Component, OnInit } from '@angular/core';
import { SearchService } from './search_service/search.service';
import { Observable } from 'rxjs/Observable';
import * as Datastore from 'nedb';
import * as electron from 'electron';
import * as path from 'path';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [SearchService]
})
export class AppComponent implements OnInit {
title = 'app';
datum;
res;
constructor(private searchService: SearchService){ }
ngOnInit(){
this.getData();
this.res = this.searchService.getDataObs();
}
getData(){
this.searchService.getData().then(res => this.datum = res);
}
}
What I get in my app on startup
Any tips on why is this happening? I don't think this is normal behaviour and presume that it has something to do with the way I create observable. I've read about bindCallback()
operator, functionality of which seems to be what I need here, since db.find()
is a callback function, but I wasn't able to implement it correctly.
Sorry for the messy code and thanks in advance
EDIT - HTML
<!--The whole content below can be removed with the new code.-->
<div style="text-align:center">
<h1>
Welcome to {{title}}!!
Data: {{datum}}
Res: {{res | async}}
</h1>
EDIT - If I add getDataObs()
method to a button, or call it 100 or so ms after the startup it returns the query as intended.