激活的路线URL始终为空

问题描述 投票:4回答:4

考虑以下服务,

@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()都会触发。但是,无论路线是什么,价值总是""(空字符串)。

这有什么不对?

angular angular-router
4个回答
8
投票

ActivatedRoute的定义是:

包含与插座中加载的组件关联的路径的信息。 ActivatedRoute也可用于遍历路由器状态树。

这意味着如果你在服务中注入它,你将从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)

6
投票

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

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

constructor(public location: Location ){ }

let currentUrl = this.location.path();

可以在NavigationEnd订阅者中使用


3
投票

角度路由器将参数发送到目标组件,只有它能够读取这些参数。

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


0
投票

我看到了很多答案,但我认为以下代码可能是一个更“优雅”的解决方案。可以按照满足您需求的方式映射所有必需值。

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
            }})
        );
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.