Angular 5获取当前的路由url及参数
获取当前加载组件的路由信息可以使用ActivatedRoute。ActivatedRoute接口如下:
interface ActivatedRoute {
snapshot: ActivatedRouteSnapshot
url: Observable<UrlSegment[]>
params: Observable<Params>
queryParams: Observable<Params>
fragment: Observable<string>
data: Observable<Data>
outlet: string
component: Type<any> | string | null
get routeConfig: Route | null
get root: ActivatedRoute
get parent: ActivatedRoute | null
get firstChild: ActivatedRoute | null
get children: ActivatedRoute[]
get pathFromRoot: ActivatedRoute[]
get paramMap: Observable<ParamMap>
get queryParamMap: Observable<ParamMap>
toString(): string
}
可以看到ActivatedRoute提供了url,params,queryParams等。ActivatedRoute这几个属性返回的是Observable,它是可以用来监控url,参数的变化。
注入使用如下:
@Component({...})
class MyComponent {
constructor(private route: ActivatedRoute) {
const id: Observable<string> = route.params.map(p => p.id); //获取参数
const url: Observable<string> = route.url.map(segments => segments.join('')); //获取拼接的url
const user = route.data.map(d => d.user); //获取数据
}
}