Angular がログインページにリダイレクトする 質問する

Angular がログインページにリダイレクトする 質問する

私は、権限のないページにアクセスしようとするユーザーが自動的にログイン ページにリダイレクトされる Asp.Net MVC の世界から来ました。

Angular でこの動作を再現しようとしています。@CanActivate デコレータを見つけましたが、コンポーネントはまったくレンダリングされず、リダイレクトも行われません。

私の質問は次のとおりです:

  • Angular はこの動作を実現する方法を提供していますか?
  • もしそうなら、どのように?それは良い習慣ですか?
  • If not, what would be the best practice for handling user authorization in Angular?

ベストアンサー1

Here's an updated example using Angular 4 (also compatible with Angular 5 - 8)

Routes with home route protected by AuthGuard

import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login/index';
import { HomeComponent } from './home/index';
import { AuthGuard } from './_guards/index';

const appRoutes: Routes = [
    { path: 'login', component: LoginComponent },

    // home route protected by auth guard
    { path: '', component: HomeComponent, canActivate: [AuthGuard] },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const routing = RouterModule.forRoot(appRoutes);

AuthGuard redirects to login page if user isn't logged in

Updated to pass original url in query params to login page

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

For the full example and working demo you can check out this post

おすすめ記事