目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
在Angular 14中,如果你这样做
this.router.url
它总是会返回'/'
您可以使用Location服务(https://angular.io/api/common/Location)及其方法“path”来获得URL,而不是使用Router(在导航生命周期中可能还没有最终路由)。这是一个比“window.location”更好的选择。pathname,”它不会感知Angular,并且会在路径中包含基本的href。
import { Location } from '@angular/common';
constructor(private location: Location) { }
ngOnInit(): void {
console.log(this.location.path()); // returns path
}
其他回答
方法1:使用Angular: this.router.url
import { Component } from '@angular/core';
// Step 1: import the router
import { Router } from '@angular/router';
@Component({
template: 'The href is: {{href}}'
/*
Other component settings
*/
})
export class Component {
public href: string = "";
//Step 2: Declare the same in the constructure.
constructor(private router: Router) {}
ngOnInit() {
this.href = this.router.url;
// Do comparision here.....
///////////////////////////
console.log(this.router.url);
}
}
方法二:窗口。如果你不想使用路由器,就像我们在Javascript中做的那样
this.href= window.location.href;
import { Router, NavigationEnd } from "@angular/router";
constructor(private router: Router) {
// Detect current route
router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
console.log(val.url);
}
});
}
新建路由器>= RC.3
最好和一个简单的方法来做到这一点是!
import { Router } from '@angular/router';
constructor(router: Router) {
router.events.subscribe((url:any) => console.log(url));
console.log(router.url); // to print only path eg:"/login"
}
当我想要根据路线改变背景时,我面临着这个问题。但它只在我浏览网站时工作,而不是当我刷新页面时。
在router.events.subscribe()中,这是事件。导航时的Url,刷新时的this。router。Url。
现在它起作用了:
import { ActivatedRoute, Router, NavigationStart } from '@angular/router';
constructor(private router: Router) {}
public ngOnInit() {
this.router.events.subscribe((events:any) => {
let theme = '';
if (events instanceof NavigationStart) { theme = events.url; }
else { theme = this.router.url; }
if(theme === '/videos') { ... }
}
这可能是你的答案,使用激活路由的params方法从你想要读取的URL/路由获取参数,下面是演示片段
import {ActivatedRoute} from '@angular/router';
@Component({
})
export class Test{
constructor(private route: ActivatedRoute){
this.route.params.subscribe(params => {
this.yourVariable = params['required_param_name'];
});
}
}