Delay for router in Angular2

拥有回忆 提交于 2019-12-11 02:47:09

问题


I have this code, which have 2 functions: say() will play the music (is implemented and it works) and router leads to next page (it works also)

go_next() {
     this.say(); // audio
     this.router.navigate( ['app'], { queryParams: { 'part': this.part+1 } } ); //go to next page 
}

But what I would like to do is to play music (it takes 5 sec) and then to go to the next page...how could I implement this?..I guess, I have to implement some kind of delay, but I can't find such parameter by router.navigate.


回答1:


setTimeout(function, milliseconds) Executes a function, after waiting a specified number of milliseconds.

go_next(){
    setTimeout(() => {
        this.router.navigate(['app'], {queryParams: {'part': this.part + 1}})
      }
      , 5000);
}



回答2:


You can take advantage of RxJS to achieve this. By making say() return an observable using Observable.create, you can emit a value asynchronously whenever it's fully completed. Within go_next(), you can utilize delay() to wait any amount of time before acting on the emitted value within subscribe(). In this case the emitted value from say() can be anything, you simply need to call next() to emit some kind of value.

This pattern could allow you to handle error and completed states of say() if necessary or depending on how say() is structured, allow multiple subscribers to react to it's value/error/completion.

say(): Observable<any> {
  return Observable.create(observer => {
    // some logic goes here
    // emit value when completed
    observer.next(true);
  });
}

go_next() {
  this.say().delay(5000).subscribe(() => {
      // this.router.navigate( ['app'], { queryParams: { 'part': this.part+1 } } );
  });
}

Here is a plunker demonstrating the functionality.

Hopefully that helps!




回答3:


You could use a resolve on the route.

import { Observable } from 'rxjs';
import { Injectable} from '@angular/core';
import { Resolve } from '@angular/router';

@Injectable()
export class DelayResolve implements Resolve<Observable<any>> {

  constructor() {
  }

  resolve(): any {
    return Observable.of('delayed navigation').delay(500);
  }
}

Then it the routes just apply the resolve:

path: 'yourpath',
component: YourComponent,
resolve: [DelayResolve],


来源:https://stackoverflow.com/questions/45310888/delay-for-router-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!