Angular路由守卫里怎么获取路由参数?
我在用Angular写一个编辑页面的路由守卫,想在canActivate里拿到路由里的id参数做权限判断,但this.route.snapshot.paramMap.get(‘id’)总是返回null,这是为啥?
我试过把ActivatedRoute注入到守卫里了,也确认路由配置里有:id参数。奇怪的是在组件里能正常拿到,但在守卫里就不行。是不是守卫执行时参数还没准备好?
<!-- Vue 示例(用于对比思路) -->
<template>
<div v-if="$route.params.id">
编辑文章 {{ $route.params.id }}
</div>
</template>
<script>
export default {
beforeRouteEnter(to, from, next) {
console.log(to.params.id); // 这里能拿到
next();
}
}
</script>
守卫执行时路由参数已经就绪了,问题是你注入的ActivatedRoute是根级别的,跟组件里用的不是一回事。直接用方法参数里的snapshot,省心。