Within my project, there exists a service designed to retrieve data from NeDB. To accomplish this task, I have implemented a method called getData()
. Upon initialization of my component, I invoke this method using the ngOnInit()
hook.
An issue arises at this juncture.
When getData()
employs promises, everything functions correctly and the query results are successfully loaded and displayed upon app startup.
Utilizing Promises in getData()
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);
});
})
}
}
However, when attempting to utilize observables within the same context, nothing is loaded or displayed; the result passed to the subscriber ends up being undefined
.
Using Observables in getData()
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);
}
}
The App's Behavior on Startup https://i.sstatic.net/5jhQ8.png
Any suggestions as to why this phenomenon is occurring? It appears abnormal to me and I suspect that it may be related to how I am creating observables. I have come across information about the bindCallback()
operator, which seems to encapsulate the required functionality since db.find()
is a callback function, but my attempts at implementing it have not been successful.
I apologize for the cluttered code and appreciate any assistance in advance.
EDIT - HTML
<!--The entire content below can be replaced with the new code.-->
<div style="text-align:center">
<h1>
Welcome to {{title}}!!
Data: {{datum}}
Res: {{res | async}}
</h1>
EDIT - If I include the getDataObs()
method within a button, or introduce a delay of approximately 100 ms post-startup, then the intended query results are retrieved.