首页 > 解决方案 > 如何在 Angular 中以 / 为起点设置经过身份验证和未经身份验证的路由?

问题描述

在我的 Angular 应用程序中,我希望有一组未经身份验证的用户的路由和一组经过身份验证的路由。例如,通过身份验证后,您应该无法在 /login 处进入登录页面。

我可以轻松设置。当我希望这两种情况的“起点”都是 / 时,真正的麻烦就来了。我的意思是,当您第一次进入网站时(当然是未经身份验证),您应该看到欢迎页面为http://example.com/。当您登录并验证自己时,您还应该只看到网址为http://example.com/

起初,如果未经身份验证,我只AppComponent渲染一个PublicComponent,如果经过身份验证,我的路由。这一直有效,直到我不得不为未经身份验证的用户实现更多页面并为此需要一个路由器;这PublicComponent还不够。

我已经尝试了几件事,但都没有奏效。在导航中找不到该组件,或者它没有显示。

现在我有路线

    {
        path: "",
        component: PublicComponent  // unauthenticated
    },
    {
        path: "pageA",
        component: PageAComponent   // unauthenticated
    }
    {
        path: "",
        component: HomeComponent,   // authenticated
        outlet: "authenticated"
    },
    {
        path: "pageB",
        component: PageBComponent,   // authenticated
        outlet: "authenticated"
    },
    {
        path: "pageC",
        component: PageCComponent,   // authenticated
        outlet: "authenticated"
    },
    {
        path: "**",
        component: PageNotFoundComponent
    }

app.component.html

  <div *ngIf="isAuthenticated(); else notAuthenticated">
    <router-outlet name="authenticated"></router-outlet>
  </div>
  <ng-template #notAuthenticated>
    <router-outlet></router-outlet>
  </ng-template>

未经身份验证的路线(没有插座)似乎可以正常工作。我可以在它们之间导航。当输入具有经过身份验证的出口的路由时,它会跳转到通配符,在这种情况下是PageNotFoundComponent. 没关系。

登录并成为经过身份验证的用户时,HomeComponent应该在 / 处向我打招呼,但它似乎也超过了其他路线。例如,当输入 /pageB 时,HomeComponent正在初始化并再次呈现。所以我尝试给它一个完整的路径匹配来阻止它覆盖其他路径。

...
    {
        path: "",
        component: HomeComponent,
        outlet: "authenticated",
        pathMatch: "full"
    },
...

现在其他页面都是空白的。没有渲染任何组件,就好像它找不到它们一样 - 但也没有错误。我可以输入任何我想要的乱码 URL,然后得到一个空白页。

我拒绝相信这是不可能做到的。因此,非常感谢任何帮助或建议!谢谢!

编辑

是的,我已经尝试过 AuthGuard,但我还不能让它与我的设置一起使用。

标签: angularangular-routing

解决方案


您应该使用 AuthGuard 来实现,然后在您的路由中指定哪个链接适用于 authGuard,就像这样。

{
    path: "pageC",
    component: PageCComponent, : canActivate: [AuthGuard]
},

然后你可以使用 Angular CLI 生成一个 AuthGuard,就像这样

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



@Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}

canActivate(
     next: ActivatedRouteSnapshot,
     state: RouterStateSnapshot): Observable<boolean> | boolean {
       if (this.auth.authenticated) { // This is the injected auth service which depends on what you are using
            return true; 
           }

       console.log('access denied!')
       this.router.navigate(['/login']);
       return false


   }

}

您还可以使用以下链接获取更多信息 https://angular.io/api/router/CanActivate


推荐阅读