Reputation: 3593
I am quite new to Angular and Javascript, so I was wondering what the following syntax means:
const simpleObservable = new Observable((observer) => {
// observable execution
observer.next("bla bla bla")
observer.complete()
})
Why is the argument "(observer)
" passed in parenthesis to the Observable constructor, and what is the arrow syntax => {...}
doing?
where can I read about those special constructs in javascript syntax?
Upvotes: 1
Views: 111
Reputation: 84902
what is the arrow syntax => {...} doing?
Arrow functions are a type of function introduced in the 2015 version of javascript. They are shorter to write and unlike normal functions they take their value of this
from the context in which they're declared, not the context in which they're invoked. (though in your particular case, this
is not being used, making that distinction irrelevant)
The equivalent using old style functions would be:
const simpleObservable = new Observable(function (observer) {
// observable execution
observer.next("bla bla bla")
observer.complete()
});
Why is the argument "(observer)" passed in parenthesis to the Observable constructor
To construct an observable from scratch, you pass in a function which describes how to do whatever it is you want done. When someone calls .subscribe
on the observable your function gets called, and you can do whatever asynchronous stuff you need. And when you have something to report, you can use the .next
, .complete
, and .error
callbacks to output the results.
Upvotes: 1
Reputation: 61339
The () => {}
syntax denotes a lambda expression. Specifically, a TypeScript lambda expression where the this
pointer is set to the actual class (instead of the lambda invoker).
JavaScript lambdas (function() {}
) should be avoided as they do not maintain the integrity of this
.
Upvotes: 1