I have a component that fetches some data from an API. The component has a loading member variable, which is used to determine whether a loading icon should be shown. When the data fetch completes, loading is set to false, in order to hide the loading icon. This should happen regardless of whether an error occurred or not.
Currently, I have implemented this as follows:
export class MyComponent implements OnInit {
loading = true;
data;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getData().subscribe(data => {
this.data = data;
this.loading = false;
},
() => {
this.loading = false;
});
}
}
I'm wondering if there is a way to eliminate the duplication of this.loading = false. If I were using Promises, this is what I'd use the Promise.finally() callback for -- but I'm not. Is there an equivalent in RxJS, or a better way to implement this?
As of RXJS 5.5, use the "finalize" operator:
ngOnInit() {
this.dataService.getData()
.pipe(
finalize(() => this.loading = false)
)
.subscribe(data => {
this.data = data;
});
}
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