Retrieving Data using HTTP Flashcards
What is observable?
A collection of items over time.
Unlike an array, it doesn’t retain items. Emitted items can be observed over time.
What does an observable do?
Nothing, until we subscribe. When we subscribe the observable emits notifications.
If everything is okay and item is emitted, next notification is emitted.
If an error occurs observable emits error notification. If there are no more items to emit, observable emits a complete notification.
Common observable usage
- Start the observable (subscribe)
- Pipe emitted items through a set of operators
- Process notifications: next. error, complete
- Stop observable (unsubscribe)
Variables that reference an observable
Should have ‘$’ as suffix
HttpClientModule needs to be included
in the imports array of the app module
Imports array of @NgModule is used for declaring
external modules
Declarations array of @NgModule is used for
declaring components, directives and pipes that belong to that module
HTTP get method returns an observable so
we will receive a notification. Which means
getProducts(): Observable {
return this.http.get(this.productUrl);
}
To handle exceptions of observable we need
tap operator- taps intor observable stream without transforming the stream,
catchError -catches the error
Subscribing to an observable
x.subscribe() or x.subscribe(Observer) or x.subscribe({ nextFn, erroFn, completeFn})
Subscribe returns subscription. We can use it later on to cancel subscription
Unsubscribing from an Observable
It’s a good thing to always unsubscribe.
- Store the subscription in a variable
- Implement the OnDestroy lifecycle hook
- Use the subscription variable to unsubscribe