我无法从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 Angular:6.1.4 ...动画,cli,通用,编译器,编译器 - 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 / core 0.7 . 4 @ angular-devkit / schematics 0.7.4 @ angular / cdk 6.4.6 @ angular / material 6.4.6 @ ngtools / webpack 6.1.4 @ schematics / angular 0.7.4 @ schematics / update 0.7.4 rxjs 6.2.2 typescript 2.7.2 webpack 4.9.2
3 回答
你可以得到这样的网址信息:
如果你需要在url中获取queryParams你可以得到:
你可以检查instanceof NavigationStart 和 NavigationEnd
这是一个例子
在
app.component.ts
Stackblitz演示
我尝试访问url或路径的组件是组件树的主机/父/并行组件 . 上述所有故障都允许捕获路径组件的正确路径
inside
,而不是父/主机/并行树组件 . 只有Router.events在那里工作 . 令人惊讶的是,我无法在父/主机内捕获并使ActivatedRoute.url.subscribe工作 .这适用于主机/父/并行树 - 或: