One thing to keep in mind is that you won't be able to access the organizations
property outside of the subscribe block due to JavaScript/TypeScript's asynchronous nature. For a more thorough understanding, you can learn about the Event Loop here. This means that you must utilize .subscribe()
to retrieve the observable value.
The issue with
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
}));
console.log(this.organizations);
is that console.log(this.organizations);
will run before the subscription completes, resulting in a value of undefined
. To correctly display organizations
, modify it as follows:
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
console.log(this.organizations);
}));
Furthermore, instead of returning the observable in the constructor as mentioned in the comments, consider returning it during the OnInit lifecycle hook.
ngOnInit(): void {
this.access.getOrganizations().subscribe((data => {
this.organizations = data;
console.log(this.organizations);
}));
}
Alternatively, you could store it as an observable initially and access it when necessary later on.
organizations: Observable<any>;
ngOnInit() {
this.organizations = this.access.getOrganizations();
}
someOthermethod() {
this.organizations.subscribe(res => {
console.log(res);
});
}