我使用 CanActivate 守卫完成了这项工作。使其工作的关键是从 canActivate 方法返回一个 Observable。这样,您可以根据需要延迟。
import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { StateService } from '../../_services/state.service';
import { Subject } from 'rxjs/Rx';
import { Subscription } from 'rxjs/Subscription';
@Injectable()
export class LoadingGuard implements CanActivate {
constructor(private state: StateService) {}
public canActivate(): Observable<boolean> {
if (!this.state.loading$.getValue()) {
return Observable.of(true);
}
let subject = new Subject<boolean>();
let subscription = this.state.loading$.subscribe(value => {
if (!value) {
subject.next(true);
subject.complete();
subscription.unsubscribe();
}
});
return subject;
}
}
上面,StateService 是一个服务,它评估当前用户并为应用程序的其余部分预缓存一些数据。它有一个名为 loading$ 的主题,加载完成后返回 false。
剩下的就是在应用模块中声明守卫。
import { LoadingGuard } from './app/loading-guard/loading-guard';
// other imports omitted
@NgModule({
// other module properties omitted
providers: [LoadingGuard]
})
export class AppModule {}
然后在你的路由中声明守卫。
import { LoadingGuard } from './app/loading-guard/loading-guard';
// other imports omitted
export const rootRouterConfig: Routes = [
{ path: 'app', component: AppComponent,
canActivate: [LoadingGuard],
children: [
{ path: 'index', component: IndexComponent },
// child routes omitted
] },
{ path: 'sign-in', component: SignInComponent },
{ path: '**', redirectTo: 'sign-in' }
];
作为参考,这里是关于 CanActivate 的文档:
https://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html