So basically this line of code
console.log("Partners " + this.partners);
is running before the code inside the .subscribe
this.dataService.getAllPartners().subscribe(data => {
// What happens here is after the request has been processed
}
Thats because the subscribe is an asynchronous operation and takes some time, so you need to do your console.log inside the subscribe.
Be aware that subscriptions are long living and need to be unsubscribed with your component like this below.
import { Subscription } from 'rxjs';
private subscription : Subscription;
ngOnInit() {
this.subscription = this.dataService.getAllPartners().subscribe(data =>
{this.partners = data;
console.log("data " + data);},
error => {
LoggerService.error('Failed to load partners.')
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
But you also should not be subscribing the way you are. Ideally you should subscribe using the | async
pipe inside your template as angular will then handle all of that for you.
So in your component do this
ngOnInit() {
this.partners = this.dataService.getAllPartners();
}
and in your template
<ng-container *ngFor="let partner of partners | async">
// Your html markup for each partner here
{{partner.name}}
</ng-container>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…