Reputation: 6867
Withing my angular app , I'm using this kind of treatment
myMethod(){
...
setTimeout(() => {
this.router.navigate(['mucomponent']);
});
}
As I was told : setTimeout
without a delay (0) seems to wait the next tick where all treatments are done to begin my treament. it's a planification for the near future.
Since I need this behaviour
Is there any clean alternative to do it the same with typescript or rxjs to do it better ?
Suggestions ?
Upvotes: 12
Views: 19028
Reputation: 1263
Even though the accepted answer might technically work, it is far from ideal. The RxJS team created the asapScheduler
for exactly this use case.
asapScheduler.schedule(() => this.router.navigate(['mucomponent']));
From the RxJS docs:
asap scheduler will do its best to minimize time between end of currently executing code and start of scheduled task. This makes it best candidate for performing so called "deferring". Traditionally this was achieved by calling
setTimeout(deferredTask, 0)
, but that technique involves some (although minimal) unwanted delay.
Upvotes: 15
Reputation: 4044
This should work, and is simpler than previous solutions:
timer(0).subscribe(time => this.router.navigate(['mucomponent']));
timer() takes 2 parameters, the second is optional. If 2 parameters are provided, the first parameter is the delay, and the second parameter is the period. If only one parameter is provided, it is the delay, and the timer will only emit 1 value (it won't repeat).
From the documentation for timer():
If period is not specified (the second parameter), the output Observable emits only one value, 0.
reference: https://rxjs-dev.firebaseapp.com/api/index/function/timer
Upvotes: 14
Reputation: 1079
You can use Interval or take in rxjs;
import { interval } from 'rxjs';
import { take} from 'rxjs/operators';
myMethod() {
interval(0).pipe(take(1),
).subscribe(value =>
this.router.navigate(['mucomponent']);
}
Upvotes: 11
Reputation: 11
If you're trying some kind of scheduler here is timeout from RxJS
https://rxjs-dev.firebaseapp.com/api/operators/timeout
Upvotes: 0