In my project, I use Observables in service to hold data taken from DB. So I subscribe to it in my main component.
In search.service, the data retrieving function
getData(){
return new Observable(subscriber => {
this.db.find({}, function(err, docs) {
if (err) subscriber.error(err);
subscriber.next(docs);
});
})
}
In main component
getData(){
this.searchService.getData().subscribe(
data => {
this.datum = data;
console.log(this.datum)},
err => console.log("E", err)
);
console.log(this.datum);
}
ngOnInit(){
this.getData();
}
Here are the results I get in the console
From this I understand that while in the context of .subscribe()
method, property datum
is assigned the contents of database, but outside of it, it is still undefined.
I don't get why it happens, or how to display the contents of DB. All the tutorials I've found suggest that after I subscribe to observable and assing in the subscription method the property of my component to result passed in observable, everything should stay this way and I should be able to display it easily in the component.
Been bashing my head against this for a month or so and had no luck with articles on observables. Seems like I get the principles but, no matter what, can't put them to use.
Any tips would be greatly appreciated.
(I don't want to resort to using promises, because observables seem a little more general in terms of their applicability and it seems that learning them is a very potent skill to have)
EDIT
The html template for the component.
<!--The whole content below can be removed with the new code.-->
<div style="text-align:center">
<h1>
Welcome to {{title}}!!
Data: {{datum}}
</h1>
EDIT 2
View