首页 文章

Angular2:注销时有条件地重定向到另一个路由

提问于
浏览
1

我在使用Angular2和路由器的特定用例上苦苦挣扎 .

假设我们有3条路线 . 主页,列表和 Profiles .

“配置文件”是一条受保护的路由:必须对用户进行身份验证才能访问此路由 .

如果用户在“ Profiles ”页面上并注销,我希望能够检测到他不再被允许进入当前页面,并将他重定向到“主页”页面 .

但是,如果他在“列表”页面上并注销,我不想做任何事情(允许用户留在这里,因为它不是一条有保障的路线) .

有人知道如何实现这一点,假设我有很多路线,我想避免在每个组件中放置这个“用户允许”逻辑吗?

2 回答

  • 0

    Summary

    在我的情况下,我喜欢通过检查我保存到本地存储的令牌的验证,让我的用户访问受保护的路由 . 因此,如果我将它们注销,我会删除令牌以及我当前在本地存储中拥有的任何数据 . 您可以在每个路线中使用此功能 .

    public logout() {
        localStorage.removeItem('profile');
        localStorage.removeItem('access_token');
        this.userProfile = undefined;
        this.router.navigateByUrl('/home');
      };
    

    我创建了一个身份验证服务 . 您可以创建两个不同的服务,或两个不同的功能 . 真的,你有很多选择 . 这是一个选择 .

    Solution

    要注销和重定向,

    public logout() {
        localStorage.removeItem('profile');
        localStorage.removeItem('access_token');
        this.userProfile = undefined;
        this.router.navigateByUrl('/home');
      };
    

    您可以在每个组件中使用此功能 . 或者页面 . 如果用户在配置文件页面上,则基本上重定向路由 . 但如果用户不在需要重定向的页面或路由上,请删除

    this.router.navigateByUrl('/home');
    

    从功能中,用户不会被重定向 .

    所以你可以有两个服务

    public.service.ts
        @Injectable()
    export class Public {
         public logout() {
            localStorage.removeItem('profile');
            localStorage.removeItem('access_token');
            this.userProfile = undefined;
          };
    

    然后在您想要将用户注销但仍保留在同一页面的页面中使用此服务

    export class SomeComponent {
           constructor( private router: Router, private public: Public  ) { }
    }
    

    所以当使用logout函数时它不会重定向 .

    然后在用户注销时重定向添加此服务,

    secure.service.ts
        @Injectable()
    export class Secure {
         public logout() {
            localStorage.removeItem('profile');
            localStorage.removeItem('access_token');
            this.userProfile = undefined;
            this.router.navigateByUrl('/home');
          };
    

    当然,任何包含该服务的组件都会在您的_2577789中调用正确的 logout function

    <a class="myClass" href="#"(click)="public.logout()">Logout</a>
    

    要么

    <a class="myClass" href="#" (click)="secure.logout()">Logout</a>
    
  • 3

    这可以通过单个(菜单)组件来实现,该组件服务于所有路线,公共和私人路线,其中私人路线仅在登录时可见 .

    这个组件还包括一个注销按钮,只有在登录时才可见 . 此处理程序注销并确定当前路由是否需要登录 . 如果是,则重定向到主页,如果不执行任何操作 .

    受保护的私有路由可能会在app.module中定义,并定义了 canActivate ,因此这些是需要登录的路径 .

    app.module.ts

    const appRoutes: Routes = [
      { path: '', component: HomeComponent },
      { path: 'sign-in', component: SignInComponent },
      { path: 'private', loadChildren: './private/private.module#PrivateModule', 
    canActivate: [LoginRouteGuardService] }
    ];
    

    menu.component.ts

    signOut() {
      // your sign out method
      // then check if redirect necessary
      if (this.router.url.includes('/private/')) {
        this.router.navigateByUrl('/');
      }
    }
    

    上面提供的变化如下:https://stackblitz.com/edit/free-vote-redirect-on-sign-out

相关问题