The promise returns a value but I don't seem to be assigning the value properly in the subscribe method.
import { Component } from '@angular/core';
import { DataService } from '../../shared/data.service';
@Component({
selector: 'topbar',
templateUrl: './src/app/components/topbar/topbar.component.html',
styleUrls: ['./src/app/components/topbar/topbar.component.css'],
providers: [DataService]
})
export class TopbarComponent {
companyCount;
constructor (private dataService: DataService){
dataService.getCompaniesCount().subscribe(res => this.companyCount = res.count); //doesn't work
dataService.getCompaniesCount().subscribe(res => console.log(res.count)); //works
}
}
With this code
res => this.companyCount = res.count
doesn't get executed immediately. WhengetCompaniesCount()
makes a request to a server, it takes a long time until the response arrives and the observable calls the function passed tosubscribe(...)
(res => this.companyCount = res.count
).The execution of the constructor,
ngOnInit
,ngAfterViewInit()
and lots of other stuff will have happened before the response arrives.You can see
like registering an event handler that gets called when an event happens.
All code that depends on the data being available needs to be properly chained.
The simplest way is to move to code into
subscribe(...)
component context "this" is not available inside of the subscribe(), to fix this, declare _this and assign this before the subscribe() as shown below;
I understand that the thread is old. So, this for the new users who are trying now. I am not sure if this is something that you are looking for. But we can persist data in a component variable albeit an ugly workaround. Here is how we used in a sample POC
(Please use the proper hooks as subsribing to an observable is not preferred in a constructor)
That was the sample component and below is the sample service