如何在同一路径的loadChildren中添加canActivate:[AuthGuard]

时间:2019-06-13 09:15:05

标签: nativescript angular2-routing nativescript-angular

我有app-routing.module.ts

const routes: Routes = [
    { path: "", redirectTo: "/fp", pathMatch: "full" },
    { path: "home", loadChildren: "~/app/home/home.module#HomeModule" },
    { path: "login", loadChildren: "~/app/accounts/login/login.module#LoginModule" },
    { path: "register", loadChildren: "~/app/accounts/registers/registers.module#RegistersModule" },
 { path: "fp", loadChildren: "~/app/accounts/first_page/first_page.module#FirstPageModule" },
];
export const routing = NativeScriptRouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules});

在Home组件中,我有home-routing.module.ts

const routes: Routes = [
    { path: "", component: HomeComponent }
];

在LoginComponent中,我有login-routing.module.ts

const routes: Routes = [
    { path: "", component: LoginComponent }
];

在RegisterComponent中,我有resgister-routing.module.ts

const routes: Routes = [
    { path: "", component: RegistersComponent }
];

在RegisterComponent中,我具有first_page-routing.module.ts

const routes: Routes = [
    { path: "", component: FirstPageComponent }
];

我这样创建一个authguard:

canActivate(): boolean {
        if (this.auth.isAuthenticated()) {
            console.log('true')
             return true;
      }
        this.router.navigate(['/login']);
        console.log('false')
         return false;
     }

我的问题是,如何在路由中使用AuthGuard?

1 个答案:

答案 0 :(得分:0)

您可以尝试在应用程序路由模块中添加防护:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    android {
    buildTypes {
    debug {
    debuggable true
    }
</application>

...假设您只想保护const routes: Routes = [ { path: '', redirectTo: '/fp', pathMatch: 'full' }, { path: 'home', loadChildren: '~/app/home/home.module#HomeModule' }, { path: 'login', loadChildren: '~/app/accounts/login/login.module#LoginModule' }, { path: 'register', loadChildren: '~/app/accounts/registers/registers.module#RegistersModule' }, { path: 'fp', loadChildren: '~/app/accounts/first_page/first_page.module#FirstPageModule', canActivate: [AuthGuard], canActivateChild: [AuthGuard], } ]; 路径。