Reputation: 723
In my Ionic 2 / Angular mobile app, I use AngulaFire2 to receive data from Firebase.
Typically, I add a LoadingController while the data is fetched from Firebase to show the user that the system is still working. The loader is dismissed, as soon as the data is received successfully, or an error occured. However, if the user is not connected to the Internet, the loader will never stop showing - continuing forever, since no data is fetched and no error occures.
I would like to add a timeout, that stops the loader after a couple of seconds and shows an alert "no connection". Then the user is able to continue using the app with the data that is already loaded to localstorage.
Any idea how to implement this is appreciated. This is an example code:
ionViewDidLoad() {
let loader = this.loadingCtrl.create({
content: "Getting data..."
});
loader.present().then(() => {
// get all products
this.productService.getAllProductsOnce().subscribe(data => {
this.allProducts = data;
loader.dismiss();
}), error => {
loader.dismiss();
this.errorService.handleError(error);
};
}
}
Upvotes: 0
Views: 735
Reputation: 309
You can use the RxJS-Timeout Operator. This will hit the error callback if the Observable does not fire within the specified amount of time (in milliseconds):
this.productService.getAllProductsOnce()
.timeout(3000)
.subscribe(data => {
this.allProducts = data;
loader.dismiss();
},
error => {
loader.dismiss();
this.errorService.handleError(error);
});
Don't forget to add the import for this Operator:
import 'rxjs/add/operator/timeout';
Upvotes: 1