当我将组件放入mat-sidenav时,我无法获取路由参数
this.route.paramMap.pipe(
tap(params => console.log(params)),
switchMap((params: Params) => {
...
})
).subscribe(
...
);
当我将组件放入mat-sidenav时,我无法获取路由参数
this.route.paramMap.pipe(
tap(params => console.log(params)),
switchMap((params: Params) => {
...
})
).subscribe(
...
);
要从路由器插座外部获取路由,您可以执行以下操作:
getActivatedRoute(): ActivatedRoute {
let route = this.router.routerState.root;
while (route.firstChild) {
route = route.firstChild;
}
return route;
}
this.getActivatedRoute().paramMap.pipe(
tap(params => console.log(params)),
switchMap((params: Params) => {
...
})
).subscribe(
...
);
Trying to write a service to my header (and any other component) can know the current route and params. Would be nice to know the currently loaded component as well but that’s less important.Hope this works.
import {Injectable} from '@angular/core';
import {ActivatedRoute, NavigationEnd, Router} from "@angular/router";
import {Observable} from "rxjs";
import {first, filter, map, switchMap} from "rxjs/operators";
@Injectable({providedIn: 'root'})
export class RouteService {
constructor(
private route: ActivatedRoute,
private router: Router
){}
public getActivatedRouteParameter(): Observable<any>
{
let params
params = this.router.events.pipe(
filter(e => e instanceof NavigationEnd),
map((): ActivatedRoute => {
let route = this.route;
while (route.firstChild)
{
route = route.firstChild;
}
return route;
}),
filter((route: ActivatedRoute) => route.outlet === 'primary'),
switchMap((route: ActivatedRoute) => route.paramMap) , first()
);
return params;
}
}