0

I'm trying to create a mobile application using the ionic 2 framework. (Written in Angular 2).

Now I have a FileUpload option in my app. But this takes a long time when the user has a poor internet connection or something went wrong within the app itself. Now what I want to achieve is to have this fileupload sort of 'timeout' after 7 seconds.

How is this possible in Angular 2?

I was thinking about a workaround having something like this (demo purpose, not the actual code):

let doneUploading: boolean = false;
this.http.post(url, data, options).subscribe(response => {
   doneUploading = true;
   ....
}, err => {
   doneUploading = true;
   ....
});

setTimeout(()=> {
  if(!doneUploading) {
    alert("TIMEOUT");
  }
}, 7000);

But this feels like quite a hacky workaround. Is there an option in Angular 2 to do this? Or should I just use the workaround?

Ivar Reukers
  • 7,560
  • 9
  • 56
  • 99
  • 1
    Do you want to cancel upload request or just to show message? – YD1m Jun 27 '17 at 09:22
  • Hmm good question, if it's possible to cancel the upload request that would be the best option. I guess you can do that by creating an object from the subscription and calling `unsubscribe`? – Ivar Reukers Jun 27 '17 at 09:23

2 Answers2

2

There is the .timeout() and .timeoutWith methods on Observable objects in RxJS.

let subscription = this.http.post(url, data, options)
    .timeout(7000, new Error("TIMEOUT"))
    .subscribe(response => {
    },
    err => {
       alert(err);
    });

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-timeout

YD1m
  • 5,845
  • 2
  • 19
  • 23
  • 1
    Ah a timeout function, that was what I was looking for. Thanks! After googling `Observable timeout` I even found that this is a duplicate question https://stackoverflow.com/questions/36719116/how-to-timeout-angular2-http-request – Ivar Reukers Jun 27 '17 at 09:29
1

If all you care about is the callback to be not executed after 7 seconds, then you can unsubscribe from your observable after 7 seconds:

let subscription = this.http.post(url, data, options)
    .subscribe(response => {
    },
    err => {
    });
setTimeout(() => {
    subscription.unsubscribe();
}, 7000);
Saravana
  • 37,852
  • 18
  • 100
  • 108
  • Liked the answer but the answer above more specifically targets the functionalities of angular/rxjs itself instead of a workaround with own timeouts – Ivar Reukers Jun 27 '17 at 09:37