【发布时间】:2018-09-06 04:55:22
【问题描述】:
我在 Angular 中使用路由来提取 url 并将其存储在全局变量中。它运行良好,除非 url 中包含“id”。
例如,我的 Url == '/site/1' 然而......
this.authService.current_route = this.router.url
// '/site' (not 'site/1' or 'site/:id')
我如何重构才能使这项工作发挥作用?
我的 html 看起来像:
<span id="sitehead"> <a [routerLink]="['/site', site.id ]" (click)="changeroute()"> Site:</a></span>
我的组件:
import { Component, OnInit, Input } from '@angular/core';
import { DataService } from '../data.service';
import { Http } from '@angular/http';
import * as d3 from 'd3';
import { AuthService } from "../services/auth.service";
import { Router } from "@angular/router";
@Component({
selector: 'app-summary',
templateUrl: './summary.component.html',
styleUrls: ['./summary.component.css'],
})
export class SummaryComponent implements OnInit {
@Input() site;
constructor(private _dataService: DataService, private http: Http, public authService: AuthService, private router:Router ) {
}
changeroute(){
this.authService.current_route = this.router.url
console.log(this.authService.current_route)
}
谢谢!!让我知道是否可以澄清
【问题讨论】:
-
带有 id 的路由是主 '/site' 路由的子路由吗?
-
this.route.snapshot.url
-
@bryan60 是的
-
为什么你有一个
routerLink和一个(click)处理程序?不是多余的吗?另外,如果可能,请发布您的 routeConfig 以更好地理解。我认为您没有为site/:id指定子路由 -
所以这不起作用的原因与 ID 参数没有任何关系,它与 Angular 的路由器范围如何运作有关。基本上,路由器的范围仅限于注入它的组件,并且它的结构像一棵树。因此,在子路由处注入的路由器会看到完整的路由,但在父路由处注入时,它会看到它当前的作用域段并且有子级,您可以通过子级递归获取完整路径。
标签: html angular typescript