Someone helped me with a async problem almost 2 months ago, it it works really nice (and I have since added allot to it), but I still have this code in my program that I am not completely sure what it does.
The original code was:
constructor(private ngZone: NgZone) { }
ngOnInit() {
this.getPosts()
.subscribe(x => {
this.apidata = x;
this.ngZone.onMicrotaskEmpty.first().subscribe(() => {
this.largestHeight();
});
});
}
Now it is so hard getting documentation on this, and I have tried on and off for the last 2 months now. They just give a deffinition, but not real examples. The actual line would be this.ngZone.onMicrotaskEmpty.first().subscribe(()
1) So ngZone basically access the zone that you are busy with and I understand this 70%
2) onMicrotaskEmpty "Notifies when there is no more microtasks enqueue in the current VM Turn".
3) first() The only explanation of this method I got was from w3school: "The first() method returns the first element of the selected elements." So what I don't understand is in the code above, what elements did I select. I tried to run a console.dir and .log on this but all I get is [object Object]
. So I would like to know the first of what elements?
4) subscribe() I do not really know why there is a subscribe here. I was under the impression that you can only subscribe to observable's/promises. Can you subscribe to anything that can give a change through, and then run the subscribe block of code when it changes? If so, what in the previous methods are the method that changes that triggered the subscribe to run?
I hope it seems that I have tried and searched for answers for the above, but everything seems to be written for people who would not need to read it in the first place ... :P
Vm is not a virtual-machine, i do not know what it is either but Zone in Angular is an execution context to help you manage multiple async operations. More about it here.
Understanding Zone
this.ngZone.onMicrotaskEmpty
is an Observable stream and first()
is an operator which returns the first value emitted by that stream since an observable stream can have many different values over time
subscribe()
is the only way to get values from that stream or be notified when there are some values being pushed to that stream
I suggest you do some reading about zone and Rxjs observables, it will clear much of your confusions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With