如何使用 CanActivateFn 隐藏链接?

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

我使用

CanActivateFn
而不是
CanActivate
来处理我的路由身份验证。

这是我的 app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { ExampleTableComponent } from './example-table/example-table.component';
import { authGuard } from '../_guards/auth.guard';
import { HomeComponent } from './home/home.component';
import { SearchComponent} from './search/search.component';
import { SettingsComponent } from './settings/settings.component';

export const routes: Routes = [
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    { path: 'home', component: HomeComponent },
    { path: 'example-table', component: ExampleTableComponent, canActivate: [authGuard] },
    { path: 'search', component: SearchComponent, canActivate: [authGuard] },
    { path: 'settings', component: SettingsComponent },
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

这是我的 auth.guard.ts:

import { CanActivateFn, Router } from '@angular/router';
import { inject } from '@angular/core';
import { AuthService } from '../_services/auth.service';
import { map } from 'rxjs';
import { EndpointService } from 'projects/lib/xp-endpoints/endpoint.service';
import { MatSnackBar } from '@angular/material/snack-bar';

export const authGuard: CanActivateFn = (route, state) => {
    const endpointService: EndpointService = inject(EndpointService)
    const authService: AuthService = inject(AuthService)
    const _snackBar: MatSnackBar = inject(MatSnackBar)
    const router: Router = inject(Router)

    return authService.PAS.pipe(
        map(pasArray => {
           /* Auth stuff */
           return false
        })
    )
};

这是我显示的链接示例:

<div class="dropdown" *ngIf="Something here that removes the link if the user doesn't have access">
    <a routerLink="/search"><button>Search</button></a>
</div>

现在发生的情况是,如果用户没有访问权限,他们仍然可以查看该链接。我希望将该链接从页面上完全删除。

angular angular2-routing canactivate
1个回答
0
投票

您可以在 authGuard 中传递一些数据:

route.data = { ...route.data, isLoggedIn: true };

然后在组件中读取:

isLoggedIn = inject(ActivatedRoute).snapshot.data['isLoggedIn'] as boolean;
© www.soinside.com 2019 - 2024. All rights reserved.