首页 > 解决方案 > 重定向到身份验证路由 Angular 的问题

问题描述

我开始使用 Angular,并尝试创建一个简单的路由保护,如果我的服务未经授权返回,则将用户重定向到登录页面。

为此,我创建了这个路由模式->

const routes: Routes = [
  {
    path: '',
    component: LoggedComponent,
    children: [
      {path: '', component: HomeComponent}
    ],
    canActivate: [RouteGuard]
  },
  {
    path: '',
    component: AuthComponent,
    children: [
      {path: '', redirectTo: '/login', pathMatch: 'full'},
      {path: 'login', component: LoginComponent},
      {path: 'signin', component: SigninComponent}
    ]
  },
];

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

这是我的警卫服务-> PS:我将默认值设置为 false。

import {Subject, Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RouteGuard implements CanActivate {

  authorized: Subject<boolean> = new Subject();

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    this.setObservable(false)
    return false;

  }

  getObservable(): Observable<boolean> {
    console.log(`starts to observe`)
    return this.authorized.asObservable();
  }

  setObservable(newState: boolean) {
    console.log(`new observable state: ${newState}`)
    this.authorized.next(newState)
  }
  
}

好的,由于该值默认返回 false,我希望路由自动重定向到 AuthComponent,因为 Auth 是我的路由 [] 中的第二个选项。对?

所以...

在 AuthComponent 我声明要观察授权状态:

import {RouteGuard} from '@acn-collections-ws/shared';

@Component({
  selector: 'acn-collections-ws-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit {

  constructor(private guard: RouteGuard, router: Router) { 
    console.log('im here');
    this.guard.getObservable().subscribe(authorized => {
    })
  }

  ngOnInit(): void {
  }

}

但是 AuthComponent 不会加载。似乎当canActivate参数返回false时,它没有去AuthComponent,它没有加载任何东西。当授权(canActivate)返回true时,正常运行。有没有人有类似的问题,可以帮助我吗?

标签: javascriptangularangular-componentsng-modules

解决方案


这就是我在使用 Firebase 进行身份验证时的做法:

export class GuardGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router){}

  async canActivate() {

    const user = await this.authService.isLogged();

    if(user){
      return true;
    }
    else {
      this.router.navigate(['login']);
      return false;
    }

  }

}

如果用户登录返回 true,则加载请求的路由,如果没有重定向到登录路由并返回 false。

这是路由:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './modules/login/pages/login/login.component';
import { SignupComponent } from './modules/login/pages/signup/signup.component';
import { HeroComponent } from './shared/components/hero/hero.component';
import { NotFoundComponent } from './shared/components/not-found/not-found.component';
import { GuardGuard } from './shared/guards/guard.guard';

const routes: Routes = [
  { path: 'home', component: HeroComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'signup', component: SignupComponent },
  { path: 'login', component: LoginComponent },
  { path: 'tasks', loadChildren: ()=> import('./modules/task/task.module').then(m => m.TaskModule), canActivate: [GuardGuard] },
  { path: 'profile', loadChildren: ()=> import('./modules/user/user.module').then(m => m.UserModule), canActivate: [GuardGuard] },
  { path: '**', component: NotFoundComponent }
];

推荐阅读