First and foremost, you cannot access the organizations
property outside of the subscribe block, because of JavaScript/TypeScript's asynchronous properties. You may read more about the Event Loop over here, as it provides a more detailed explanation. Therefore, you will need to use .subscribe()
to return the observable value.
The problem with
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
}));
console.log(this.organizations);
is that console.log(this.organizations);
will finish executing before the subscription is completed, hence it will print a value of undefined
. The correct way of printing organizations
is to do this instead:
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
console.log(this.organizations);
}));
In addition, as explained on the comments, you should not be returning the observable on the constructor. I recommend you to return it on the OnInit life cycle instead.
ngOnInit(): void {
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
console.log(this.organizations);
}));
}
Alternatively, you may store it as an observable instead, and return it later when you really need it.
organizations: Observable<any>;
ngOnInit() {
this.organizations = this.access.getOrganizations();
}
someOthermethod() {
this.organizations.subscribe(res => {
console.log(res);
});
}