canActivate應用

某些連結在使用者登入之後才能連接,用canActivate來保護這些頁面,避免使用者在知道url的情況下,可以直接連到這些頁面。

1. 定義canActivate

創建一個auth.guard.ts檔案,當user資訊存在的時候,return true;不存在的時候,重新導向到登入頁面。(AuthService放在頁面最下方)

1
2
3
4
5
6
7
8
9
10
11
12
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isAuth()) {
return true;
} else {
this.router.navigate(['/login']);
}
}
}

2. 路由設定

app.routing.module.ts保護指定路由,並加上providers:

1
2
3
4
5
6
7
8
9
const routes: Routes = [
...,
{ path: 'protectedUrl', component: ProtectedComponent, canActivate: [AuthGuard] }
]

@NgModule({
...,
providers: [AuthGuard]
})

AuthService

而在AuthService的設定是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@Injectable()
export class AuthService {
authChange = new Subject<boolean>();
private user: User;

constructor(private router: Router) {}

registerUser(authData: AuthData) {
this.user = {
email: authData.email,
userId: Math.round(Math.random() * 10000).toString()
};
this.authSuccessfully();
}

login(authData: AuthData) {
this.user = {
email: authData.email,
userId: Math.round(Math.random() * 10000).toString()
};
this.authSuccessfully();
}

logout() {
this.user = null;
this.authChange.next(false);
this.router.navigate(['/login']);
}

getUser() {
return { ...this.user };
}

isAuth() {
return this.user != null;
}

private authSuccessfully() {
this.authChange.next(true);
this.router.navigate(['/training']);
}
}