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()
Share:
13,097

Related videos on Youtube

user3690823
Author by

user3690823

Updated on July 11, 2022

Comments

  • user3690823
    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
    Frank Modica almost 7 years
    I 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 like setTimeout, so it behaves like $timeout in Angular 1.
  • Frank Modica
    Frank Modica almost 7 years
    The 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 do import '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
    JGFMK over 6 years
    If 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
    JGFMK over 6 years
    For 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
    Robin Dijkhof over 6 years
    .take(1) might fix that.
  • JanBrus
    JanBrus about 5 years
    The solution provided by Frank Modica is also mentioned here angular.io/guide/observables so i consider this the correct solution