繁体   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