What causes this issue is because API calls in Angular are performed asynchronously, i.e The whole other parts of your program get executed regardless of whether the API call has returned the results or not. API calls can take some time to finish, and for this reason, making them run on their own thread helps to prevent glitches or stalls in your application. As a results, when you console.log() your global variable, it will be null.
So somehow, we want to wait for the API call until it finishes then we can successfully update our global variable.
A simple solution is using an Angular built-in class called BehaviorSubject. I won't explain further about it, I will just show how it gets the job done.
globally declare your variable this way:
productBehaviourSubject: BehaviorSubject<any> = new BehaviorSubject<any>(0);
And now, the subscribe body, will look like this:
this.httpClient.get('your URL').subscribe((response)=>{
this.productBehaviourSubject.next(response as Product);
});
Assuming that you are fetching a product. If it's a list of products, simply replace this.productBehaviourSubject.next(response as Product);
with this.productBehaviourSubject.next(response as Product[]);
You can now access this variable globally with updated changes.
However now, to use this.productBehaviourSubject
, you need to subscribe to it and do whatever that you want to do inside the body of the subscribe method. Like this
this.productBehaviourSubject.asObservable().subscribe( (product)=> {
console.log(product)
// Do your stuff here
// And it can only be inside this method.
// outside this method, values will be null.
})
Now you can pass around this.productBehaviourSubject
to any component, it will work fine