【发布时间】:2019-02-08 03:07:48
【问题描述】:
我无法从 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},
];
我的版本:
Angular CLI:6.1.4 节点:10.7.0 操作系统:linux x64 角度:6.1.4 ... 动画、cli、common、编译器、compiler-cli、核心、表单 ... http、语言服务、平台浏览器 ...平台-浏览器-动态,路由器
包版本
@angular-devkit/architect 0.7.4 @angular-devkit/build-angular 0.7.4 @angular-devkit/build-optimizer 0.7.4 @angular-devkit/build-webpack 0.7.4 @angular-devkit/核心 0.7.4 @angular-devkit/原理图 0.7.4 @角/cdk 6.4.6 @角/材料6.4.6 @ngtools/webpack 6.1.4 @原理图/角度 0.7.4 @原理图/更新 0.7.4 rxjs 6.2.2 打字稿2.7.2 webpack 4.9.2
【问题讨论】:
-
如我所见,您还没有在路由中使用 DashboardComponent。并从“redirectTo: '/login'”中删除斜杠
-
它没有帮助。它可能也无济于事。我的问题是
/teams路由没有被捕获为/或路径为""我会担心如果它只是/login -
似乎它只适用于带有构造函数的事件捕获 - 如果你注意到了
-
stackblitz.com/edit/… 看这个演示.. 在这里我可以使用路由器获取 url
-
Aniket,在本演示中查看 app.component 中的结果。 stackblitz.com/edit/…
标签: javascript angular url path angular-router