Angular 2 - Cancelling a subscription after a timeout
13,097
Solution 1
A plain setTimeout
should work:
let subscription = this.http.get(mysqlUrl).subscribe(...);
setTimeout(() => subscription.unsubscribe(), 5000);
Solution 2
You could use the takeUntil operator:
this.http.get(mysqlUrl)
.takeUntil(Observable.of(true).delay(5000))
.subscribe(...)
Solution 3
import 'rxjs/add/operator/timeout
this.http.get(mysqlUrl)
.timeout(5000)
.subscribe()
Related videos on Youtube
Author by
user3690823
Updated on July 11, 2022Comments
-
user3690823 almost 2 years
I want to ignore a response from my API if it is taking too long. I use
this.http.get(mysqlUrl).subscribe()
to get the response. But I want to cancel that subscription if it takes longer than 5 seconds to finish. I know I can use unsubscribe(), but how can I link that to a timeout value?
Thanks!
-
Frank Modica almost 7 yearsI think people just don't like when
setTimeout
is used as a hack. But in this particular case, you actually want to wait for a timeout. Also, Angular 2 patches async functions likesetTimeout
, so it behaves like$timeout
in Angular 1. -
Frank Modica almost 7 yearsThe more I use
rxjs
the more I like this answer, since you don't have to store the subscription in a variable. I'm just not crazy about having to doimport 'rxjs/add/operator/takeUntil'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/delay'
. But if I was managing many subscriptions I might use this solution. -
JGFMK over 6 yearsIf you have a successful subscription - ie response is returned, before the 5 seconds your error handling kicks in too after the 5 seconds as well, so I'm not such a fan of this approach. It's a shame the successful subscribe doesn't just automatically end the timeout and that was it...
-
JGFMK over 6 yearsFor me the takeUntil didn't stop after 5 seconds. My scenario involved using a clickstream in conjunction with a switchmap, The clickstream meant I wanted to cancel any ongoing requests if another click came in before first completed..
-
Robin Dijkhof over 6 years
.take(1)
might fix that. -
JanBrus about 5 yearsThe solution provided by Frank Modica is also mentioned here angular.io/guide/observables so i consider this the correct solution