重定向到 auth 路由的问题 Angular

Problems to redirect to auth route Angular

我开始与 Angular 合作,我正在尝试创建一个简单的路由保护,以在我的服务 return 未经授权的情况下将用户重定向到登录页面。

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

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)
  }
  
}

好的,因为默认值为 returning 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 参数 returns 为 false 时,它​​不会转到 AuthComponent,它不会加载任何东西。当授权(canActivate)return为真时,正常运行。有没有人有类似的问题可以帮助我?

这是我在使用 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;
    }

  }

}

如果用户已登录 return true,则加载请求的路由,如果不重定向到登录路由,则 return 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 }
];