typescript AuthGuard在Angular中无法正常工作

yv5phkfx  于 2023-04-07  发布在  TypeScript
关注(0)|答案(1)|浏览(162)

在“我的应用程序”中,我在成功登录后重定向到主页,

  • 当用户登录时,我在本地存储中将isLoggedIn设置为true
  • 但是当我刷新主页时,它再次重定向到登录页面,但是isLoggedIn仍然设置为true。
<form (ngSubmit)="onLogin()" name="loginForm" [formGroup]="loginForm">
        <div class="userInput">
          <mat-form-field class="full-width" appearance="outline">
            <mat-label>UserID</mat-label>
            <input
              formControlName="name" matInput placeholder="Enter User ID" required/>
            <mat-error *ngIf="!loginForm.controls['name'].valid">
                UserID is required
            </mat-error>
          </mat-form-field>
        </div>
        <div>
          <span>
            <a class="text-link" class="aLink" routerLink="/auth/forgot-password">Forgot Password?</a>
          </span>
          <mat-form-field class="full-width" appearance="outline">
            <mat-label>Password</mat-label>
            <input formControlName="password" matInput [type]=" hide ? 'password' : 'text'" required />
            <button  mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide Password'"
            [attr.aria-pressed]="hide">
            <mat-icon>
                {{hide ? 'visibility_off' : 'visibility'}}
            </mat-icon>
        </button>
        <mat-error *ngIf="!loginForm.controls['password'].valid">
            Password is required
          </mat-error>
        </mat-form-field>
        </div>
        <button mat-flat-button style="background-color: #16bca8">Login</button>
</form>

上面是我的login.component.html

redirecting(){
    this.userService.logIn();
    const observer= {
        next: (x:any) => {console.log(x)}, 
        error: (err: any) => {console.log(err.error)}
    }
    this.http.get(this.url,{responseType: 'text' ,withCredentials: true}).subscribe(observer);
    
    this.router.navigate(['home']);
  }

  onLogin() {
    let body = {
      "username": username,
      "password": password
    }
    const observer = {
      next: (x: any) => {console.log(x);this.redirecting()}, 
      error: (err: any) => {console.log(err.error)}, 
      complete: () => console.log('Observer got a complete notification'),
    }
    this.http.post(url, body, { responseType: 'text', withCredentials: true }).subscribe(observer);
  }

上面是我的login.component.ts

ngOnInit() {
        this.isLoggedIn = localStorage.getItem("loggedin") === "true";
    }
    loggedIn():boolean {
        return this.isLoggedIn || this.isRegistered;
    }
    logIn() {
        this.isLoggedIn = true;
        localStorage.setItem("loggedin", "true");
    }

上面是我正在使用的服务

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree 
    {
    
        if (this.userService.loggedIn()) {
            console.log("Authorized");
            return true;
        } else {
            console.log("Not Auhtorized");
            this.router.navigate(['login']);
            return false;
        }
    }

上面是auth.guard.ts

{ path: '',   redirectTo: '/home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
    { path: 'professor', component: ProfessorComponent },
    { path: 'login', component: LoginComponent },
}

我已经在申请中添加了上述路线。
任何帮助将不胜感激。谢谢!

fykwrbwg

fykwrbwg1#

你的AuthGuard是好的。当然它可以写得更好,但它正在工作。但在刷新服务返回false的loggedIn()。
在您的服务上,您正在调用onInit来检查本地存储(如果已登录)。

ngOnInit() {
 this.isLoggedIn = localStorage.getItem("loggedin") === "true";
}

OnInit()将不适用于服务,请参阅Lifecycle hooks
为什么不直接从函数的本地存储中获取日志信息呢?(或者在OnInit上使用构造函数)

loggedIn():boolean {
 return localStorage.getItem("loggedin") === "true";
}

logIn() {
 localStorage.setItem("loggedin", "true");
}

相关问题