In this link is code with part of my application: stackblitz.com/edit/angular-wfpjb8 . This show, what is my problem. (pay attention on console.log in console)
SHORT DESCRIPTION: In Angular 6 I have component search, where I have input. When I press ENTER, get some data from DB in httpService service:
keyDownFunction(event){
if(event.keyCode == 13) {
this.httpService.searchPoint().subscribe(
points => {
this.mapService.setSearchPoints(points);
this.router.navigate(['/home/search/']);
});
}
}
From backend I receive some of data in format: [{}, {}, {}, {}...] and this data I send throught mapService to component ResultComponent, where I want to display this data. mapService:
setSearchPoints(points){
this.pointList.next(points);
}
getSearchPoints(){
return this.pointList.asObservable();
}
Component ResultsComponent, where I subscribe data from service and want to display data.
export class ResultsSearchComponent {
points;
constructor(private mapService: MapService) {
this.mapService.getSearchPoints().subscribe((points) => {
console.log('1: ', points);
this.points = points;
});
console.log('2: ', points);
}
PROBLEM:
- When I first time set data from backend, console.log 1 doesn't execute (so my data from backend won't be written) and console.log 2 execute undefined - I want to see data from DB immediately
- When I second time set data from backend (when component ResultsComponent exist) console.log 1 write correct data from backend, and console.log 2 doesn't execute. (all works good)
- When I close this component and set data from backend one more time console.log 1 write correct data (but this execute is from the last one set), but 2 doesn't execute.
- When I close this component one more time, console.log 1 write twice, when I close one more time execute three times, four times, five times and so on...
I really don't understand why it works like this, because in my mind, it should work properly Please, tell me, what I am doing in the wrong way.