首页 > 解决方案 > AuthGuard 防止 Angular Material 完全加载

问题描述

我正在为我的 Ionic 4 项目添加 AuthGuard。守卫检查用户是否登录,如果为真,则用户继续到主页,如果为假,则用户被重定向到登录页面。问题是当用户被重定向到登录页面时,因为 Angular Material 标签无法正常工作。在不涉及守卫的情况下访问登录页面时,一切正常。

AuthGuard 服务:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router';
import { UserService } from './user.service';
import { AngularFireAuth } from '@angular/fire/auth';
import { auth } from 'firebase/app';


@Injectable({
  providedIn: 'root'
})

export class AuthService implements CanActivate {

  constructor(
      private router: Router,
      public afAuth: AngularFireAuth,
      private user: UserService) { 

  }

  canActivate(route: ActivatedRouteSnapshot): Promise<boolean> {

        return new Promise((resolve, reject) => {

            this.afAuth.auth.onAuthStateChanged(user => {

                if (user) {

                    // User is signed in.

                    resolve(true);

                } else {

                    // No user is signed in.

                    resolve(false);

                    this.router.navigate(['login']);

                }

            });

        });

    }

}

login.page.html

<ion-content>

  <div class="blue-background">
    <img src="assets/logo.png" width="33%" height="18.6%" style="display: block;  margin-left: auto;  margin-right: auto;"/>
  </div>

    <div class="form_wrapper">
      <div class="form_container">
        <div class="row clearfix">
          <div class="">

            <mat-form-field appearance="outline" style="height: 40px; margin-bottom: 1.5em;">
              <mat-label>Email</mat-label>
              <input matInput style="min-height: 40px;" type="email" [(ngModel)]="username">
            </mat-form-field>

            <mat-form-field appearance="outline" style="height: 40px; margin-bottom: 1.5em;">
              <mat-label>Password</mat-label>
              <input matInput style="min-height: 40px;" type="password" [(ngModel)]="password">
            </mat-form-field>

            <ion-button style="margin-top: 10px; float: right; overflow: auto" fill="clear" size="small" color="dark" (click)="goToForgotPassword()">Forgot password?</ion-button>
            <ion-button style="clear: both; overflow: auto" fill="solid" expand="block" color="dark" (click)="login()">Login</ion-button>

        </div>
      </div>
    </div>
  </div>
</ion-content>

字段应如何工作的图像。

AuthGuard 重定向后字段如何工作的图像。请注意标签不会浮动。

标签: angular-materialionic4

解决方案


推荐阅读