【问题标题】:Why is Angular router.navigate() not navigating?为什么 Angular router.navigate() 不导航?
【发布时间】:2020-04-16 10:04:09
【问题描述】:

我正在用 Angular 构建身份验证。登录后,应重定向用户。我的问题是 router.navigate() 函数似乎不起作用...... 这是不起作用的代码:

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] }
];

auth 模块路由:

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

【问题讨论】:

  • 开发者控制台有错误吗?
  • @Çağrı 不,它只显示 console.log(this.router)。
  • 你可以为你的代码创建堆栈闪电战
  • 你去家务模块的路线在哪里?
  • @SayoojVR 我忘了添加它们,它们现在在帖子中。

标签: javascript angular typescript routing


【解决方案1】:

在 Github 上检查您的代码,我想说的问题是导航被您的 AuthGuard 阻止。

AuthGuard 正在调用 authService 的 isLoggedIn 函数,该函数检查本地存储中的用户数据,而 authState 订阅者仍在写入本地存储。

这种事情可以工作也可以不工作,这几乎是运气和localstorage api的工作速度。

我建议您在 isLoggedIn 函数中检查 AuthService 的变量 user 而不是 localstorage。如果用户变量未定义,您可以检查 localstorage。

这应该是相对节省的,但是我不知道登录函数返回和 authState 订阅者触发之间的时间。您可能希望在登录函数中设置用户变量。 signInWithEmailAndPassword 函数确实返回一个带有凭据的 Promise,该凭据上有一个用户属性。

您可以将登录功能更改为

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

还有isLoggedIn函数

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

哦,为了完整起见,您可能应该在注销函数中将用户变量设置为 undefined 或 null。即使用户注销,用户数据仍然在内存中徘徊

【讨论】:

    猜你喜欢
    • 2019-08-15
    • 2018-03-04
    • 2018-01-19
    • 2019-07-12
    • 2018-08-29
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多