Angular6 Router Guard多次调用

时间:2018-10-09 06:21:19

标签: javascript angular6 router auth-guard

我正在开发一个使用angular6的应用程序,我的应用程序路由包含许多子路由,我注意到我的应用程序多次调用router auth防护,这导致我的应用在从页面导航到另一个页面时速度很慢。

到目前为止,我的代码: 路由器

const mainRoutes: Routes = [

    {
    path:"",
    component:MainComponent,
    canActivate:[AuthGuard],
    canActivateChild:[AuthGuard],
    children:[
      {path:'',loadChildren:"./calendar/calendar.module#CalendarModule"},
      {path:'patients',loadChildren:"./patients/patients.module#PatientsModule"},

    ]
  },

];

每个模块都包含另一个也具有路由器的模块。

auth.guard.ts:

 canActivate(): Observable<boolean> {
        return this.checkLogin();
    }
    canActivateChild(): Observable<boolean> {
        return this.checkLogin();
  }
  canLoad(route: Route): Observable<boolean>|Promise<boolean>|boolean {
    return this.checkLogin();

}
    //authguard can provide an observable rather than a straight boolean
    checkLogin(): Observable<boolean> {
            return this.authService.checkAuth().map(e => {
                if (e == false) {
                    this.router.navigate(['auth'], );
                    return false;
                }
                return true;
            }).catch(() => {
                console.log("Could not login");
                this.router.navigate(['auth'], );
                return Observable.of(false);
            });
    }

checkAuth:

checkAuth(): Observable<boolean> {
        return this.http.get(HttpService.serverApiUrl+"security/check-auth")
            .map(response => {
                if(response['auth'] == 1) {
          return true;
                } else {
          this.router.navigate(['/auth'])
                    return false;
                }
            });
    }

enter image description here

0 个答案:

没有答案