簡體   English   中英

為什么 Angular router.navigate() 無法導航?

[英]Why is Angular router.navigate() not navigating?

我正在 angular 中構建身份驗證。 登錄后,應重定向用戶。 我的問題是 router.navigate() function 似乎不起作用......這是不起作用的代碼:

async login() {
 if(!this.email || !this.password) {
   return;
 }
 this.showSpinner = true;
 this.authService.login(this.email, this.password).then(
   (data) => {
     this.router.navigate(['/chore/show']);
     console.log(this.router);
   },
   (error) => {
     this.error = error.message;
     this.showSpinner = false;
   }
 );
}

當登錄成功時,console.log 會顯示,但它不會導航到 chore/show 路由。

應用路線:

const routes: Routes = [
 { path: '', redirectTo: 'auth', pathMatch: 'full' },
 { path: 'auth', loadChildren: './modules/auth/auth.module#AuthModule' },
 { path: 'chore', loadChildren: 
 './modules/chore/chore.module#ChoreModule', canActivate: [AuthGuard] }
];

認證模塊路線:

const routes: Routes = [
 { path: 'login', component: LoginComponent },
 { path: 'register', component: RegisterComponent},
 { path: '', redirectTo: 'login', pathMatch: "full"}
];

和家務模塊路由:

const routes: Routes = [
 { path: 'show', component: ShowChoreComponent},
 { path: '', redirectTo: 'show', pathMatch: 'full' },
];

由於某種原因,我無法在登錄后重定向它。 有什么建議么? 編輯:添加了應用程序路線。 代碼在https://github.com/tomgelmers/stack

檢查 Github 上的代碼,我會說問題是導航被您的 AuthGuard 阻止。

AuthGuard 正在調用您的 authService 的 isLoggedIn function,它檢查本地存儲中的用戶數據,而 authState 訂閱者仍在寫入本地存儲。

這種事情可以工作也可以不工作,這很幸運,本地存儲 api 工作的速度有多快。

我建議您在 isLoggedIn function 中檢查 AuthService 的變量用戶而不是本地存儲。 如果用戶變量未定義,您可以檢查 localstorage。

那應該相對節省,但是我不知道登錄 function 返回和 authState 訂閱者觸發之間的時間。 您可能希望在登錄 function 中設置用戶變量。 signInWithEmailAndPassword function 確實返回了一個 Promise ,其憑據上有一個用戶屬性。

您可以將登錄 function 更改為

async login(email: string, password: string) {
  return this.afAuth.signInWithEmailAndPassword(email, password).then(userData => {
     this.user = userData.user
     return userData
  }
}

而 isLoggedIn function 到

get isLoggedIn(): boolean {
   if(this.user) return !!this.user
   const  user  =  JSON.parse(localStorage.getItem('user'));
   return  user  !==  null;
}

哦,為了完成,您可能應該在注銷 function 中將用戶變量設置為未定義或 null。 即使用戶注銷,用戶數據仍然在 memory 中徘徊

暫無
暫無

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

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