Pipes and Observables
Let’s learn why pipes are useful when handling `Observables` in the template.
We'll cover the following...
Asynchronous code in Angular is almost an inseparable technique used in this framework. So, the ability to handle it is crucial. When do asynchronous calls appear? The most common scenario is when we have to send an HTTP
request to display some data.
Observables in Angular
Let’s get back to the profile card task we implemented in the last tasks. The data context was simplified a bit compared to a standard application in which the user data needs to be fetched from an API before it’s displayed.
If we want the data context to be simplified, user data will no longer be supplied as a simple data object. Instead, it’ll be retrieved through another service. Because the fetch is asynchronous, the output of the service call will be an Observable User
rather than a User
object. Let’s look at the example below:
export class AppComponent implements OnInit{
user$: Observable<User>;
constructor(
private userService: UserService,
) {
}
ngOnInit() {
// get user from the service (as Observable)
this.user$ = this.userService.getUser();
}
}
The user$
property is Observable
, so we can’t simply use it to display the data in the template. Instead, we have to subscribe to the asynchronous data that finally comes and ...