我将进一步讨论Eliseo的答案。他所说的是对的,但这只是一个部分的回答。
真正的答案是改变我的
恩贡尼特
对此:
ngOnInit() {
this.spinnerSubscription = this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map(route => route.firstChild),
switchMap(route => route.data),
switchMap(data => {
if (!data.disableSpinner)
return this.spinnerService.onLoadingChanged
else
return of(false);
})
).subscribe(loading => this.loading = loading);
}
完成后,我可以在如下路径中使用数据:
const routes: Routes = [
{ path: '', redirectTo: '/', pathMatch: 'full' }, // Put first so it redirects :)
{ path: '', component: HomeComponent, data: { state: 'home' } },
// Lazy load
{ path: '', loadChildren: './widget/widget.module#WidgetModule', data: { state: 'widget', disableSpinner: true } }, // Put this last as it has empty path
// 404
{ path: '**', component: HomeComponent }, // 404?
]
这里有一点需要注意;如果您正在使用
延迟加载
你
必须
确保数据对象是初始声明的一部分。
我有我的
data
在我的
小部件路由模块
但它被忽视了。
我希望这能帮助别人。
PS:为了确保这确实能帮助其他人,这里是我的整个组件:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { Subscription, of } from 'rxjs';
import { SpinnerService } from '../services/spinner.service';
import { switchMap, filter, map } from 'rxjs/operators';
@Component({
selector: 'pyb-spinner',
templateUrl: './spinner.component.html',
styleUrls: ['./spinner.component.scss']
})
export class SpinnerComponent implements OnInit, OnDestroy {
loading: boolean;
private spinnerSubscription: Subscription
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private spinnerService: SpinnerService
) { }
ngOnInit() {
this.spinnerSubscription = this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map(route => route.firstChild),
switchMap(route => route.data),
switchMap(data => {
if (!data.disableSpinner)
return this.spinnerService.onLoadingChanged
else
return of(false);
})
).subscribe(loading => this.loading = loading);
}
ngOnDestroy() {
if (this.spinnerSubscription) this.spinnerSubscription.unsubscribe();
}
}