使用angularfire2和firebase的Angular 5身份验证应用.该应用程序可以使用应用程序内链接进行精确导航,例如在登录后重定向到仪表板或通过应用程序中的按钮/链接链接到另一个页面(组件).但是,如果在" http:// localhost:4300/dashboard "页面上我点击了浏览器刷新(Chrome),它会将我重定向回登录页面.在浏览器上使用BACK/NEXT工作正常 - 但我想因为我并没有特别要求去特定的路线.
我有一个NavBar,通过使用订阅,识别我是否登录(见右上方截图...) - 这一切都正常.
我猜测在浏览器刷新或直接URL导航时,它会在确定我是否已经过身份验证之前尝试加载页面.开发控制台从我插入导航栏组件的console.log语句中建议这一点,并且在Angular核心建议我们以开发模式运行之前它们是"未定义"的事实:
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 …Run Code Online (Sandbox Code Playgroud) 所以我真的很接近这个问题.基本上,我有登录工作,我有代码设置来监视onAuthStateChanged,但问题是,当我刷新页面,即使用户当前登录,它仍然重定向到/login页面,因为我有auth警卫设置,检查用户是否已登录.
我有一个auth服务设置,可以进行所有身份验证检查.
在我的auth服务构造函数中,这就是我onAuthStateChanged设置代码的地方:
constructor(
private auth: AngularFireAuth,
private router:Router,
private db:AngularFireDatabase,
) {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// What do I need to put here to ensure that the auth guard goes to the intended route?
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的auth guard的canActivate()方法:
canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean> {
if(this.authService.getAuthenticated()) {
return Observable.of(true);
} else {
this.router.navigate(['/login']);
}
}
Run Code Online (Sandbox Code Playgroud)
这是getAuthenticated()方法:
getAuthenticated() {
return firebase.auth().currentUser;
}
Run Code Online (Sandbox Code Playgroud)
更新:
以下是用户实际登录时调用的方法.在实际组件中,这是登录方法:
login(data, isValid) {
if(isValid) {
this.authService.login(data.email, data.password)
.then(
(data) …Run Code Online (Sandbox Code Playgroud) javascript firebase angularfire firebase-authentication angular
我正在使用AngularFire2.这就是我接近我的AuthGuard服务的方式:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
this.af.auth.subscribe((auth) => {
if(auth == null) {
this.router.navigate(['/login']);
this.allowed = false;
} else {
this.allowed = true;
}
})
return this.allowed;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码有效,除非我直接访问受保护的页面(我在浏览器中输入URL),它在订阅解析为true后不会加载相应的组件.
在角度1中,保护路线是确保在路线加载之前先解决某些事情.
它出现在角度2中,路由加载(无论是真还是假,并且不等待来自线路的任何响应),因此当订阅值返回为真时,我必须转到另一条路线,然后返回在它工作之前.
什么是保护我的路线在Angular 2中响应的正确方法?