简体   繁体   English

Angular 6:所有路线上的防护都不起作用

[英]Angular 6: Guard on all routes is not working

I'm trying to make the frontend secured by only letting certain Id's getting access.我试图通过只让某些 Id 获得访问权限来保护前端。 I want that If someone try to enter any route except for /login/:id , he'll get page-not-found if he didn't logged already, but it's not working.我希望如果有人尝试输入除/login/:id之外的任何路由,如果他还没有登录,他会得到 page-not-found,但它不起作用。

These are my routing table and guard:这些是我的路由表和守卫:

EDIT: I solved the problem and update the code:编辑:我解决了问题并更新了代码:

app-routing.module.ts app-routing.module.ts

 // Routing array - set routes to each html page const appRoutes: Routes = [{ path: 'login/:id', canActivate: [AuthGuard], children: [] }, { path: '', canActivate: [AuthGuard], canActivateChild: [AuthGuard], children: [{ path: '', redirectTo: '/courses', pathMatch: 'full' }, { path: 'courses', component: CourseListComponent, pathMatch: 'full' }, { path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' }, { path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent, children: [{ path: '', component: CourseListComponent }, { path: 'lesson/:lessonId', component: CourseLessonComponent, data: { type: 'lesson' } }, { path: 'quiz/:quizId', component: CourseQuizComponent, data: { type: 'quiz' } } ] } ] }, { path: '**', component: PageNotFoundComponent, pathMatch: 'full' } ];

auth.guard.ts auth.guard.ts

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> { // save the id from route snapshot const id = +route.params.id; // if you try to logging with id if (id) { this.authUserService.login(id); // if there was error - return false if (this.authUserService.errorMessage) { this.router.navigate(["/page_not_found"]); return false; } // there wasn't any errors - redirectTo courses and // continue else { this.router.navigate(["courses"]); return true; } } // if you already logged and just navigate between pages else if (this.authUserService.isLoggedIn()) return true; else { this.router.navigate(["/page_not_found"]); return false; } } canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> { return this.canActivate(route, state); }

auth-user.service.ts auth-user.service.ts

 export class AuthUserService implements OnDestroy { private user: IUser; public errorMessage: string; isLoginSubject = new BehaviorSubject<boolean>(this.hasToken()); constructor(private userService: UserService) {} // store the session and call http get login(id: number) { this.userService.getUser(id).subscribe( user => { this.user = user; localStorage.setItem('user', JSON.stringify(this.user)); localStorage.setItem('token', 'JWT'); this.isLoginSubject.next(true); }, error => this.errorMessage = <any>error ); } // if we have token the user is loggedIn // @returns {boolean} private hasToken(): boolean { return !!localStorage.getItem('token'); } // @returns {Observable<T>} isLoggedIn(): Observable<boolean> { return this.isLoginSubject.asObservable(); } // clear sessions when closing the window logout() { localStorage.removeItem('user'); localStorage.removeItem('token'); this.isLoginSubject.next(false); } ngOnDestroy() { this.logout(); }

So I managed to solve this problem.所以我设法解决了这个问题。 I added to the route of login/:id children: [] and changed the isLoggedIn to be behaviorSubject so the token won't change after refresh or moving between pages and it worked.我添加到 login/:id children: [] 的路由中,并将 isLoggedIn 更改为行为主题,因此在刷新或在页面之间移动后令牌不会更改并且它起作用了。 I updated the code in the post so everyone could see the solution我更新了帖子中的代码,以便每个人都可以看到解决方案

change this line:改变这一行:

const id = route.params.id;

to

const id = +route.params.id; // to convert from string to number (it's string from route params)

and one more thing, I'm not sure you should navigate to a page not found like you did ['**']还有一件事,我不确定您是否应该像以前那样导航到找不到的页面 ['**']

instead do this: ['/page_not_found']而是这样做:['/page_not_found']

now I know that 'page_not_found' does not exist in your route but that's the point, because of it, the user will be redirected to a page not found as you wanted现在我知道您的路线中不存在“page_not_found”,但这就是重点,因此,用户将被重定向到您想要的未找到的页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM