我无法从 ActivatedRoute 或路由器导入中获取 URL 或路径。它为路径“”输出空白,为 URL 输出“/”。我记得使用的是工作版本。唯一捕获正确路由的是 Router.events。我也无法订阅 ActivatedRoute 中的 URL。这是代码
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router, ActivatedRoute, UrlSegment, NavigationStart, RoutesRecognized } from '@angular/router';
@Component({
selector: 'api-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
routePath: string = '';
constructor(
private _r: Router,
private _ar: ActivatedRoute) {
this._r.events.subscribe((event: any) => {
if (event instanceof RoutesRecognized) {
// '/teams' output with route http://localhost:4200/teams
console.log(event.url);
}
// NavigationStart // NavigationEnd // NavigationCancel // NavigationError // RoutesRecognized
});
}
ngOnInit() {
console.log(this._ar.pathFromRoot.toString()); // Blank output with route http://localhost:4200/teams
console.log(this._ar.routeConfig.path.toString()); // Blank output with route http://localhost:4200/teams
console.log(this._ar.snapshot.url); // Blank output with route http://localhost:4200/teams
this._ar.url.subscribe((urlsegment: UrlSegment[]) =>{
console.log(urlsegment) // Unable to subscribe with route change to /teams
})
}
}
我在这里遗漏了什么吗?我看过这个Angular router url returns slash
我的路线:
const APPMainRoutes: Routes = [
{path: '', redirectTo: '/login', pathMatch: 'full'},
{path: 'teams', component: CollaborateComponent},
{path: 'login', component: LoginComponent},
];
我的 ng 版本:
Angular CLI:6.1.4 节点:10.7.0 操作系统:linux x64 Angular :6.1.4 ... 动画、cli、通用、编译器、编译器-cli、核心、表单 ... http、语言服务、平台浏览器 ... 平台浏览器动态,路由器
包版本
@angular-devkit/架构师 0.7.4 @angular-devkit/build-angular 0.7.4 @angular-devkit/构建优化器 0.7.4 @angular-devkit/build-webpack 0.7.4 @angular-devkit/核心 0.7.4 @angular-devkit/原理图 0.7.4 @ Angular/CDK 6.4.6 @ Angular/ Material 6.4.6 @ngtools/webpack 6.1.4 @schematics/Angular 0.7.4 @示意图/更新0.7.4 RXJS 6.2.2 typescript 2.7.2 网络包 4.9.2
最佳答案
你可以这样获取 url 信息:
ngOnInit() {
console.log(this._r.url);
}
如果需要获取url中的queryParams 你可以获得:
this._r.snapshot.queryParamMap
关于javascript - 无法从 Angular 路由器获取路径或网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52143306/