在Angular中的AuthGuard回调后重定向

时间:2019-11-06 14:02:48

标签: angular auth-guard

我有两条路线需要角度canActivate: [AuthGuard]

const routes: Routes =  [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  {
    path: 'projects', 
    children: [
      { path: '', component: ProjectsComponent , canActivate: [AuthGuard] },
      { path: 'sjcl', component: HashgenComponent, canActivate: [AuthGuard]  },
    ]
  },
  { path: 'login', component: LoginComponent },
  { path: '**', redirectTo: '/home', pathMatch: 'full' }
];

如您所见,如果用户未登录,他将被重定向到/login的路由,该路由由我的AuthGuard

if (this.auth.isLoggedIn) { return true; }

return this.auth.currentUserObservable.pipe(
  take(1),
  map(user => {
    console.log('user: ', user);
    return !!user
  }),
  tap(loggedIn => {
    console.log("loggedIn: ", loggedIn);
    if (!loggedIn) {
      console.log("access denied");
      //this.router.navigate(['/login']);
      this.router.navigate(['login'], { queryParams: { returnUrl: state.url } });
    }
  })
);

我的login组件如下,

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { AngularFireAuth } from '@angular/fire/auth';
import { FirebaseUISignInSuccessWithAuthResult, FirebaseUISignInFailure } from 'firebaseui-angular';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  returnUrl: string;

  constructor(
    public auth: AuthService, 
    private router: Router,
    private route: ActivatedRoute,
    public afAuth: AngularFireAuth) {
      this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
      console.log("yes i am here");
      console.log(this.returnUrl);
     }

  ngOnInit() {}
  ngAfterViewInit(){

  }
  successCallback(signInSuccessData: FirebaseUISignInSuccessWithAuthResult) {
    console.log("Logged in!"+this.returnUrl);
    this.router.navigateByUrl(this.returnUrl);
  }

  errorCallback(errorData: FirebaseUISignInFailure) {
    console.log("Login failure!");
  }
}

PROBLEM

现在,除了一件事以外,其他所有东西都工作正常。假设

  • 我从/home开始,然后单击/projects并登录,登录后我将重定向到/projects。 (这里没问题)
  • 我从/home开始,然后单击/projects/sjcl并登录,登录后我将重定向到/projects/sjcl。 (这里没问题)
  • 我从/home开始,单击/projects,然后单击/projects/sjcl并登录,登录后我将被重定向到/projects,而我应该重定向到/projects/sjcl(问题在这里)

问题是,

  this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  console.log("yes i am here");
  console.log(this.returnUrl);
如果已加载LoginComponent并从另一个Authguard再次调用,则不会调用

。我尝试使用不同的生命周期,甚至将其放在构造函数上也无济于事。

每次加载LoginComponent时应如何调用上面的代码段?

1 个答案:

答案 0 :(得分:0)

不要使用路由snapshot,而要听路由更改。 Router拥有您可以订阅的活动。相应地更新您的“返回” URL。