如何正确使用CanActivate进行子路由?

问题描述 投票:0回答:1

我使用CanActivate功能为我的路由器和它的孩子,但它不起作用 - 已使用相同的几个月前,但现在没有。

没有错误,警告或类似的东西,我可以调试...应用程序刚刚运行,我可以到达路由器我想保护正常的所有其他路线。

你可以看看以下代码有什么问题吗?问题是我甚至没有得到任何错误。

正如Info我使用的是Angular 5。

app.router.ts

export const router: Routes = [

    { path: '', redirectTo: 'home', pathMatch: 'full'},
    { path: 'home', component: HomeComponent},
    { path: 'signup', component: SignupComponent},
    { path: 'dashboard', canActivate: [ AuthguardGuard ],
            children:
            [
                { path: '', loadChildren: './dashboard/dashboard.module#DashboardModule', pathMatch: 'full' }
            ]
    },

    { path: '**', redirectTo: 'page-not-found' }

];

export const appRoutes: ModuleWithProviders = RouterModule.forRoot(router);

dashboard.module.ts

const dashboardRoutes: Routes = [

    { path: 'user', redirectTo: 'user', pathMatch: 'full' },
    { path: 'user', component: UserComponent,
        children: [
            { path: '', component: EditComponent },
            { path: 'userMail', component: UserMailComponent },
            { path: 'userSettings', component: UserSettingsComponent}
        ]
    },
];

authguard.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './_service/auth.service';


@Injectable()
export class AuthguardGuard implements CanActivate {
    constructor( private user: AuthService ) {
        console.log('In AuthGuard!');
    }
    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.user.isUserAuthenticated();

    }
}

auth.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {

    public isUserAuthenticated;
    private userName;

    constructor() {
        this.isUserAuthenticated = false;
    }

    setUserLoggedIn() {
        this.isUserAuthenticated = true;
    }

    getUserLoggedIn() {
        return this.isUserAuthenticated;
    }

}
angular canactivate
1个回答
1
投票

问题解决了...我从app.router.ts删除了这部分:

{path: '', loadChildren: './dashboard/dashboard.module#DashboardModule', pathMatch: 'full'}

并使用如下:

export const router: Routes = [

    { path: '', redirectTo: 'home', pathMatch: 'full'},
    { path: 'home', component: HomeComponent},
    { path: 'signup', component: SignupComponent},
    { path: 'dashboard', canActivate: [ AuthguardGuard ],
        children:[
           { path: '', component: EditComponent },
           { path: 'userMail', component: UserMailComponent },
           { path: 'userSettings', component: UserSettingsComponent}
        ]
    },

    { path: '**', redirectTo: 'page-not-found' }
];
export const appRoutes: ModuleWithProviders = RouterModule.forRoot(router);

我可以到达authguard.guard.ts文件,我可以直接得到预期的结果。

© www.soinside.com 2019 - 2024. All rights reserved.