如果用戶沒有通過Angular2/AngularFire2認證,將用戶重定向到登錄頁面的最佳方式是什麼?重定向到登錄頁面,如果沒有用AngularFire登錄2
例如;我想保護/儀表板頁面未經過身份驗證的用戶。用戶應立即被重定向到/登錄頁,
我使用
- angular2版本2.0.0-RC.1
- angular2 /路由器 2.0版。 0-rc.1
- firebase version 3.0.5
- angularfi re2版本2.0.0-beta.1
如果用戶沒有通過Angular2/AngularFire2認證,將用戶重定向到登錄頁面的最佳方式是什麼?重定向到登錄頁面,如果沒有用AngularFire登錄2
例如;我想保護/儀表板頁面未經過身份驗證的用戶。用戶應立即被重定向到/登錄頁,
我使用
可以保護採用了棱角分明2的UI路由器監護條件的網址。 https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard
使用火力
衛隊組件
注意它可能會更好,以取代在這裏引用AF,與認證服務的一個例子。
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AngularFire } from 'angularfire2';
@Injectable()
export class CanActivateViaAuthGuard implements CanActivate {
user;
constructor(private af: AngularFire, private router: Router) {
this.af.auth.subscribe(user => {
if (user) {
this.user = user;
} else {
this.user = undefined;
}
});
}
canActivate() {
if (this.user) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
申請途徑
import { CanActivateViaAuthGuard} from './CanActivateViaAuthGuard';
const routes: Routes = [
{path: '/Login', component: LoginComponent},
{path: '/dashboard', component: DashboardComponent, canActivate: [CanActivateViaAuthGuard]}
];
export const routing = RouterModule.forRoot(routes);
最後登錄代碼
onSubmit() {
this.af.auth.login({
email: this.email,
password: this.password,
}).then(() => {
this.submitted = true;
this.router.navigate(['/dashboard', this.dashboard]);
});
}
您可以在此處使用Auth方法。
if ($scope.auth === null) {
$state.go('login');
}
注入你的$ firebaseAuth並將其分配給$ scope.auth然後讓若其真正的支票或假
這看起來不像Angular2的代碼 –
感謝您的anwser,但我要求AngularFire2,而不是1 :) –
這是angularfire 2,哦,現在我看到你的意思是角2 –
找到了解決辦法。
由於todo-angular-2從R-公園
import { ReflectiveInjector } from '@angular/core';
import { Router } from '@angular/router-deprecated';
import { AuthService } from './auth-service';
let appInjector: ReflectiveInjector;
/**
* This is a workaround until `CanActivate` supports DI
* @see https://github.com/angular/angular/issues/4112
*/
export class AuthRouteHelper {
static dependencies(): {auth: AuthService, router: Router} {
const injector: ReflectiveInjector = AuthRouteHelper.injector();
const auth: AuthService = injector.get(AuthService);
const router: Router = injector.get(Router);
return {auth, router};
}
static injector(injector?: ReflectiveInjector): ReflectiveInjector {
if (injector) appInjector = injector;
return appInjector;
}
static requireAuth(): boolean {
const { auth, router } = AuthRouteHelper.dependencies();
if (!auth.authenticated) router.navigate(['/SignIn']);
return auth.authenticated;
}
static requireUnauth(): boolean {
const { auth, router } = AuthRouteHelper.dependencies();
if (auth.authenticated) router.navigate(['/Tasks']);
return !auth.authenticated;
}
}
什麼Angular2版本,什麼路由器版本? –
@GünterZöchbauer對不起,忘了。 angular2版本2.0.0-rc.1和angular2/router版本2.0.0-rc.1,firebase版本3.0.5,angularfire2版本2.0.0-beta.1 –
此路由器也被棄用。或者堅持使用'@ angular/router'或者遷移到新的V3 alpha.7路由器。您可以在新檢查的路由器上使用警衛,然後重新定向。 –