Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Cancelling a subscription after a timeout

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!

like image 677
user3690823 Avatar asked Mar 14 '26 06:03

user3690823


2 Answers

A plain setTimeout should work:

let subscription = this.http.get(mysqlUrl).subscribe(...);

setTimeout(() => subscription.unsubscribe(), 5000);
like image 63
Frank Modica Avatar answered Mar 16 '26 00:03

Frank Modica


You could use the takeUntil operator:

this.http.get(mysqlUrl)
    .takeUntil(Observable.of(true).delay(5000))
    .subscribe(...)
like image 30
JB Nizet Avatar answered Mar 15 '26 22:03

JB Nizet