Angular2取消路由转换(使用异步解析器时)

时间:2016-12-13 20:28:08

标签: angular angular2-routing

最近我开始玩Angular2。 我开始使用这样的解析器:



export class SomeResolver implements Resolve<[Day]> {
  constructor(private api: API) {}
  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
   ):Observable<any> {
    return this.api.get('days')
  }
}
&#13;
&#13;
&#13;

我实现了基本的加载程序代码:

&#13;
&#13;
export class LoaderComponent {
  @HostBinding('class.active') active:boolean = false;

  constructor(private router: Router, private location: Location) {
    router.events.subscribe(this.handleRouteChange.bind(this));
  }

  onCancelButtonClicked() {
    this.active = false;
    //Any idea? 
  }

  private handleRouteChange(event: Event) {
    if (event instanceof NavigationStart) {
      console.log('START');
      this.active = true;
    } else
      console.log('END');
      this.active = false;
    }
  }
}
&#13;
&#13;
&#13;

想象一下,this.api.get('days')执行缓慢,你想取消该请求,例如&#34; xhr.abort()&#34;并回到以前的路线。 我尝试使用&#34; location.back()&#34;但是此路由更改只是加入路由器队列。与&#34; router.navigate(...)&#34;相同。 我无法找到即时取消请求并返回上一个路线的方法。

你知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您可以创建另一个在给定时间后发出错误并将其与您的请求合并的observable。请参阅以下演示中的示例。

我在这里创建了一个流,在返回请求之前发出错误 ,因此合并的流以错误结束,从而导致取消路由转换

如果请求流中的值来自$timeout流发出的错误,则路由将被解析。 (您可以在此处使用此代码:http://jsbin.com/wiyawolete/edit?js,console

&#13;
&#13;
// this stream represents your .get request
const request$ = Rx.Observable.interval(5000).take(1);

// and this is the show-stopper
const timeout$ = Rx.Observable.timer(1000).switchMap(Rx.Observable.throw());

request$.merge(timeout$).take(1)
  // the subscription here is just to show the result.
  // you won't put it in your resolver
  .subscribe(console.log.bind(console), () => console.error('REJECTION'));
&#13;
<script src="https://unpkg.com/@reactivex/rxjs@5.0.0-beta.7/dist/global/Rx.umd.js"></script>
&#13;
&#13;
&#13;