简体   繁体   English

Angular2中路由器的延迟

[英]Delay for router in Angular2

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) 我有这个代码,它有两个功能: say()将播放音乐(已实现并且有效)和router引导到下一页(它也有效)

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 . 但我想做的是播放音乐(需要5秒),然后转到下一页......我怎么能实现这个?...我想,我必须实现某种delay ,但我找不到router.navigate这样的参数。

setTimeout(function, milliseconds) Executes a function, after waiting a specified number of milliseconds. setTimeout(function,milliseconds)在等待指定的毫秒数后执行函数。

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

You can take advantage of RxJS to achieve this. 您可以利用RxJS来实现这一目标。 By making say() return an observable using Observable.create , you can emit a value asynchronously whenever it's fully completed. 通过使say()使用Observable.create返回一个observable,只要它完全完成,就可以异步发出一个值。 Within go_next() , you can utilize delay() to wait any amount of time before acting on the emitted value within subscribe() . go_next() ,您可以使用delay()等待任何时间,然后再对subscribe()的发出值执行操作。 In this case the emitted value from say() can be anything, you simply need to call next() to emit some kind of value. 在这种情况下, say()的发出值可以是任何值,你只需要调用next()来发出某种值。

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(),或者取决于say()的结构,允许多个订阅者对其值/错误/完成做出反应。

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. 这是一个展示功能的plunker

Hopefully that helps! 希望这有帮助!

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],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM