使用 Angular 路由器获取 URL
Get the URL with Angular Router
我需要在位于 App 组件中的组件(我的 Nav 组件)中获取我当前的路由(使用 Router),但是因为它已经加载,所以点击它不会刷新,我在导航中的功能组件没有返回任何新的 URL。
我怎样才能让新的 URL 与我的导航组件一起使用?
这是我的应用程序组件:
<app-nav></app-nav>
<body>
<div class="container">
<router-outlet></router-outlet>
</div>
</body>
这是我的导航组件 (.ts) :
ngOnInit() {
console.log(this.router.url);
if(this.router.url == "/") {
this.color = "large";
this.logoPath = "assets/logos/w-logo-full.png";
} else {
this.color = "small";
this.logoPath = "assets/logos/c-logo-full.png";
}
当我的应用程序导航在每个组件中时它都在工作,但自从我移动它后它就不再工作了..
您需要订阅 ActivatedRoute 服务
像这样:
添加激活路由:
constructor(
protected route: ActivatedRoute,
...) {
}
添加添加订阅:
this.route.url.subscribe(value => {
....
});
import {
ActivatedRoute
} from '@angular/router';
export class AppComponent implements OnInit {
constructor(private route: ActivatedRoute) {
console.log("current route is " + route);
}
}
您可以使用可观察的路由器服务事件
app.component
constructor( public router: Router,) {
}
public ngOnInit(): void {
this.router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
console.log(this.router.url);
// ...
}
});
}
NavigationEnd An event triggered when a navigation ends successfully.
我需要在位于 App 组件中的组件(我的 Nav 组件)中获取我当前的路由(使用 Router),但是因为它已经加载,所以点击它不会刷新,我在导航中的功能组件没有返回任何新的 URL。 我怎样才能让新的 URL 与我的导航组件一起使用?
这是我的应用程序组件:
<app-nav></app-nav>
<body>
<div class="container">
<router-outlet></router-outlet>
</div>
</body>
这是我的导航组件 (.ts) :
ngOnInit() {
console.log(this.router.url);
if(this.router.url == "/") {
this.color = "large";
this.logoPath = "assets/logos/w-logo-full.png";
} else {
this.color = "small";
this.logoPath = "assets/logos/c-logo-full.png";
}
当我的应用程序导航在每个组件中时它都在工作,但自从我移动它后它就不再工作了..
您需要订阅 ActivatedRoute 服务
像这样: 添加激活路由:
constructor(
protected route: ActivatedRoute,
...) {
}
添加添加订阅:
this.route.url.subscribe(value => {
....
});
import {
ActivatedRoute
} from '@angular/router';
export class AppComponent implements OnInit {
constructor(private route: ActivatedRoute) {
console.log("current route is " + route);
}
}
您可以使用可观察的路由器服务事件
app.component
constructor( public router: Router,) {
}
public ngOnInit(): void {
this.router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
console.log(this.router.url);
// ...
}
});
}
NavigationEnd An event triggered when a navigation ends successfully.