最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Route params not available in guards - Stack Overflow

programmeradmin0浏览0评论

Why isn't id available in the below guard?

@Injectable()
export class ProjectDetailsGuard implements CanActivate {

    constructor(private activatedRoute: ActivatedRoute) { }

    canActivate() {
        const id = this.activatedRoute.snapshot.params['id'];

        console.log(id); // <-- undefined
    }

}

The same code works perfectly when implemented inside ponents.

Why isn't id available in the below guard?

@Injectable()
export class ProjectDetailsGuard implements CanActivate {

    constructor(private activatedRoute: ActivatedRoute) { }

    canActivate() {
        const id = this.activatedRoute.snapshot.params['id'];

        console.log(id); // <-- undefined
    }

}

The same code works perfectly when implemented inside ponents.

Share Improve this question asked Aug 25, 2017 at 15:01 Alex LomiaAlex Lomia 7,23513 gold badges58 silver badges94 bronze badges 1
  • 1 Please look at angular.io/api/router/CanActivate, canActivate is passed the route data. – jlareau Commented Aug 25, 2017 at 15:06
Add a ment  | 

1 Answer 1

Reset to default 12

The ActivatedRoute can provide params only after the route is activated. If need to get params before it is activated i.e in canActivate method, try with ActivatedRouteSnapshot

canActivate(activatedRoute: ActivatedRouteSnapshot) {
    const id = activatedRoute.params['id'];

    console.log(id); 
}
发布评论

评论列表(0)

  1. 暂无评论