每当页面重新加载或URL更改发生时,每次都会调用typescript文件

时间:2018-01-04 19:24:25

标签: angular typescript session login angular5

我需要在angular 5应用程序中实现一个会话。我想写一个ts文件,基本上,这个ts文件验证用户是否登录。每当页面重新加载或URL更改发生时,我都希望每次调用此ts文件。如何实施?

1 个答案:

答案 0 :(得分:-1)

使用AuthGuard

创建一个auth-guard.service.ts。

import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

  canActivate() {
    console.log('i am checking to see if you are logged in');
    return true;
  }

  canActivateChild() {
    console.log('checking child route access');
    return true;
  }

}

之后在您的路由文件中:

export const appRoutes: Routes = [
  {
    path: 'dashboard',
    children: [
      {
        path: '',
        canActivate: [AuthGuard],
        component: DashboardComponent
      },
      {
        path: 'users',
        component: DashboardUsersComponent,
        canActivateChild: [AuthGuard],
        children: [
          {
            path: '',
            component: DashboardUsersHomeComponent
          },
          {
            path: ':username',
            component: DashboardUserDetailsComponent,
            canDeactivate: [CanDeactivateGuard]
          }
        ]
      }
    ]
  }
]; 

以下是您的几个参考链接。

https://scotch.io/courses/routing-angular-2-applications/canactivate-and-canactivatechild

https://www.concretepage.com/angular-2/angular-2-4-route-guards-canactivate-and-canactivatechild-example

https://ryanchenkie.com/angular-authentication-using-route-guards