可以通过在组件内部订阅路由事件来获取当前URL。具体而言,可以在组件内声明路由对象,并在ngOnInit方法中订阅路由事件。这样,可以在路由事件中更新当前URL,并在需要时使用该URL。
示例代码如下:
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
@Component({ selector: 'app-example', templateUrl: './example.component.html', styleUrls: ['./example.component.css'] }) export class ExampleComponent implements OnInit {
currentUrl: string;
constructor(private router: Router, private activatedRoute: ActivatedRoute) { }
ngOnInit() { this.router.events.subscribe((event) => { if (event instanceof NavigationEnd) { this.currentUrl = event.url; } }); }
}
在上述示例中,我们使用router.events来订阅路由事件,并在NavigationEnd事件发生时更新当前URL。然后,我们可以在组件中使用currentUrl属性来访问当前URL。请注意,这只是一种解决方法,还有其他方法可以解决该问题。