已激活的路线 URL 始终为空

Activated Route URL Always Empty

考虑以下服务,

@Injectable()
export class SagasService {
    constructor(private route : ActivatedRoute, private router : Router ){
    router.events
        .filter(e => e instanceof NavigationStart)
        .subscribe(e=>{
            route.url.subscribe(a=>console.log(a[0].path));
        });
    }
}

每次路线改变时,console.log() 触发。但是,无论路由是什么,值始终是 ""(空字符串)。

这里有什么问题?

ActivatedRoute的定义是:

Contains the information about a route associated with a component loaded in an outlet. An ActivatedRoute can also be used to traverse the router state tree.

这意味着如果你在服务中注入它,你将从 AppComponent 中获得 ActivatedRoute。它将始终具有 "".

的路径

你可以像

一样遍历​​状态树找到最后激活的路由
this.router.events.pipe(
 filter(event => event instanceof NavigationEnd),
 map(() => this.activatedRoute),
 map(route => {
   while (route.firstChild) {
    route = route.firstChild;
   }
   return route;
  }),
  map(route => route.url)
 )
.subscribe( // ... do something with the url)

angular路由器将参数发送给目标组件,只有它才能读取这些参数。

但是,您可以在 RoutesRecognized 等服务中使用路由器事件来访问 url 参数。

如果你想获取当前URL,你可以从angular/common导入位置导入,如下所示

import {Location} from '@angular/common';

constructor(public location: Location ){ }

let currentUrl = this.location.path();

可以在 NavigationEnd 订阅者中使用

我看到很多答案,但我认为下面的代码可能是更 'polished' 的解决方案。 所有必需的值都可以按照您的需要进行映射。

export class AppTitleComponent implements OnInit, OnDestroy {
public id$ : Observable<number>;

constructor(
    private _router: Router,
    private _activatedRoute : ActivatedRoute
) { }

ngOnInit() {
    this.id$ = GeneralFunctions.GetRouteValues({
        router : this._router,
        activatedRoute : this._activatedRoute
    }).pipe(
      map( d => +d.params.id)
    )
}

以下功能可供使用:

import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd, Params, Data } from '@angular/router';
import { filter, map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable()
export class GeneralFunctions {
   constructor() {
   }

   public  static GetRouteValues({router, activatedRoute}: { 
        router: Router; 
        activatedRoute: ActivatedRoute; 
    })  : Observable<{
        route: ActivatedRoute;
        params: Params;
        data: Data;
    }> {
        return router
            .events
            .pipe(
                filter(e => 
                e instanceof NavigationEnd
            ),          
                map(() => 
                activatedRoute
            ),          
            map(route => {
                if (route.firstChild) {
                    route = route.firstChild;
                }
                return route;
            }),
            filter(route => 
                route.outlet === 'primary'
            ),
            map(route => { return  {
                route : route,
                params : route.snapshot.params,
                data : route.snapshot.data
            }})
        );
   }
}