0

我实际上正在学习 Angular 和 firebase,我想在用户仪表板中添加一个路由保护,这样只有登录的用户才能查看该页面。身份验证工作正常,但我在限制没有登录用户访问用户仪表板时遇到问题这是我下面的代码。

验证服务.service.ts

@Injectable({
      providedIn: 'root'
    })
    export class AuthServiceService {

      newUser: any;
      // passing Error message
      private eventAuthError = new BehaviorSubject<string>('');
      eventError$ = this.eventAuthError.asObservable();
      showSuccessCreated: boolean;

      constructor( private authz: AngularFireAuth, private db: AngularFirestore, private route:Router) 
      { } 
      // geting user details
      getUserState() {
       return this.authz.authState;
      }

      // LoggIn Users
      login(email: string , password: string ) {
        this.authz.auth.signInWithEmailAndPassword(email, password)
        .catch( error => {
          this.eventAuthError.next(error);
      }).then(userCredential => {
        if (userCredential) {
          this.route.navigate(['/dashboard']);
        }
      });
      }

这是 Authguard 服务,我尝试从我的 authservice.service.ts 中引用登录方法,但尽管我没有登录,但它仍然重定向到用户的仪表板。

authguard.service.ts

export class AuthguardService implements CanActivate {
  constructor(private authservice: AuthServiceService, private route: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    let isAuthenicated = !!this.authservice.login;
    if(isAuthenicated ){
     return true;
    }
    console.log('Access denied');
    this.route.navigate(['/login']);
    return false;
  }
}

路由.module.ts

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate:[AuthguardService],
     children: [
      {path: '', redirectTo: 'employees', pathMatch: 'full'},
      {path: 'employees', component: EmployeelistComponent, resolve: {employeeList: ResolverGuardService}},
      {path: 'detail/:id', component: EmployeeDetailComponent,  canActivate: [CanActivateGuardService],

      { path: 'notfound', component: PageNotFoundComponent},

     ]
    },



];
4

1 回答 1

0

我意识到您正在调用一个名为 login 的方法,该方法处理对 AuthGuard 类的承诺。

您必须正确处理您的登录方法才能获得正确的响应并将其保存到 isAuthenicated 变量中。

您也许可以执行类似于以下代码的操作。

身份验证服务.ts

login(): Promise<boolean> {
  // create new promise and handle our login flow 
  return new Promise((resolve, reject) => {
    // get email and password somehow
    const = email = this.getEmail();
    const = password = this.getPassword();
    // call sign in with email and password
    return this.authz.auth.signInWithEmailAndPassword(email, password)
     .catch( error => {
       this.eventAuthError.next(error);
       // reject our promise on error
       reject(false);
      })
      .then(userCredential => {
       if (userCredential) {
         // resolve our login promise
         resolve(true);
       } else {
         // reject our promise on userCredential falsy value
         reject(false);
       }
     });
  });
}

AuthGuard.ts

 export class AuthguardService implements CanActivate {
      constructor(private authservice: AuthServiceService, private route: Router) { }

      async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // handling our promise properly with asnyc/await
        const isAuthenicated = await this.authservice.login();
        if(isAuthenicated ){
          // here we allow enter the page dashboard or any other
          return true;
        }
        console.log('Access denied');
        this.route.navigate(['/login']);
        return false;
      }
    }
于 2020-02-17T17:01:56.710 回答