簡體   English   中英

Angular 5可以激活重定向到瀏覽器刷新時登錄

[英]Angular 5 canActivate redirecting to login on browser refresh

使用angularfire2和firebase的Angular 5身份驗證應用。 該應用程序可以使用應用內鏈接進行精確導航,例如在登錄后重定向到儀表板或通過應用程序中的按鈕/鏈接鏈接到另一個頁面(組件)。 但是,如果在“ http:// localhost:4300 / dashboard ”頁面上我點擊了瀏覽器刷新(Chrome),它會將我重定向回登錄頁面。 在瀏覽器上使用BACK / NEXT工作正常 - 但我想因為我並沒有特別要求去特定的路線。

我有一個NavBar,通過使用訂閱,識別我是否登錄(見右上方截圖...) - 這一切都正常。

登錄頁面

我猜測在瀏覽器刷新或直接URL導航時,它會在確定我是否已經過身份驗證之前嘗試加載頁面。 開發控制台從我插入導航欄組件的console.log語句中建議這一點,並且在Angular核心建議我們以開發模式運行之前它們是“未定義”的事實:

Developer Tools Console

app.routes:

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

import { LoginComponent } from './views/login/login.component';
import { DashboardComponent } from './views/dashboard/dashboard.component';
import { ProfileComponent } from './views/profile/profile.component';

import { AuthGuard } from './services/auth-guard.service';

const appRoutes: Routes = [
  {
    path: '',
    component: LoginComponent
  },
  {
    path: 'dashboard',
    canActivate: [AuthGuard],
    component: DashboardComponent
  },
  {
    path: 'profile',
    canActivate: [AuthGuard],
    component: ProfileComponent
  },
  {
    path: '**',
    redirectTo: ''
  }
];

export const AppRoutes = RouterModule.forRoot(appRoutes);

AUTH-gaurd:

import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
  status: string;

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

  canActivate() {
    this.authService.authState.subscribe(state =>
      this.status = state.toString());

    console.log('Can Activate ' + this.authService.authState);
    console.log('Can Activate ' + this.authService.isLoggedIn());
    console.log('Can Activate ' + this.status);

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

    this.router.navigate(['/']);
    return false;
  }
}

auth.service:

import { Injectable } from '@angular/core';
import { Router } from "@angular/router";

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';
import { GoogleAuthProvider, GoogleAuthProvider_Instance } from '@firebase/auth-types';
import { userInfo } from 'os';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class AuthService {
  private user: Observable<firebase.User>;
  private userDetails: firebase.User = null;

  public authState = new Subject();

  constructor(private _firebaseAuth: AngularFireAuth, private router: Router) { 
    this.user = _firebaseAuth.authState;

    this.user.subscribe((user) => {
      if (user) {
        this.userDetails = user;
        this.authState.next('Logged In');
        //console.log(this.userDetails);
      } else {
        this.userDetails = null;
        this.authState.next('Not Logged In');
      }
    });
  }

  isLoggedIn() {
    if (this.userDetails == null) {
      return false;
    } else {
      return true;
    }
  }
}

NAV-bar.component:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-nav-bar',
  templateUrl: './nav-bar.component.html',
  styleUrls: ['./nav-bar.component.css']
})
export class NavBarComponent implements OnInit {
  status: string;

  constructor(private authService: AuthService) {
    console.log('Constructor ' + this.status);
  }

  ngOnInit() {
    //this.authService.isLoggedIn().subscribe((state) => this.status = state.toString());
    this.authService.authState.subscribe(state =>
      this.status = state.toString());
    console.log('ngOnInit ' + this.status);
  }
}

在頁面刷新時直接調用canActivate()方法。 所以它總是返回false

canActivate() {
  this.authService.authState.subscribe(state => {
    this.status = state.toString(); // This is called async/delayed.
  });
  // so method execution proceeds

  // isLoggedIn() returns false since the login stuff in AuthService.constructor
  // is also async:    .subscribe((user) => { /* delayed login */ });
  if(this.authService.isLoggedIn()) {
    return true;
  }

  // so it comes here
  this.router.navigate(['/']); // navigating to LoginComponent
  return false;                // and canActivate returns false
}

解決方案:

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

// ...

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
  // when the user is logged in and just navigated to another route...
  if (this.authService.isLoggedIn) { return true; } 

  // proceeds if not loggedIn or F5/page refresh 

  // Store the attempted URL for redirecting later
  this.authService.redirectUrl = state.url;

  // go login page
  this.router.navigate(['/']);
  return false;
}

現在,回到稍微改變的AuthService :(這里只更改/相關代碼)

export class AuthService {

  // new
  redirectUrl: string;

  // BehaviorSubjects have an initial value.
  // isLoggedIn is property (not function) now:
  isLoggedIn = new BehaviorSubject<boolean>(false);

  // params declared private and public in constructor become properties of the class
  constructor(private firebaseAuth: AngularFireAuth, private router: Router) {
    // so this.user is not required since it is reference to this.firebaseAuth
    this.firebaseAuth.authState.subscribe((user) => {
      if (user) {
        this.loggedIn.next(true);

        // NOW, when the callback from firebase came, and user is logged in,
        // we can navigate to the attempted URL (if exists)
        if(this.redirectUrl) {
          this.router.navigate([this.redirectUrl]);
        }
      } else {
        this.loggedIn.next(false);
      }
    }
  }

}

注意:我已經在答案框中編寫了這段代碼並將其編譯在我的大腦中。 所以可能存在錯誤。 此外,我不知道這是否是最好的做法。 但這個想法應該清楚?!

基於角度路由指南

似乎有類似的問題/解決方案: Angular 2 AuthGuard + Firebase Auth

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM