【问题标题】:Why doesnt change value in auth.guard?为什么不改变 auth.guard 中的值?
【发布时间】:2018-10-15 09:42:38
【问题描述】:

我有一个变量loggined,我使用logTog() 方法更改了它的值。在此方法中,我向传输当前结果to auth.guard 的服务发出请求。在控制台“未定义”为什么以及如何解决?

AppComponent代码:

export class AppComponent implements OnInit {
    loggined: boolean = false;

    constructor(private galleryService: GalleryService) {}
    
    ngOnInit() {
        this.logTog();
    }
    
    logTog(): void {
        this.loggined = !this.loggined;
        this.galleryService.auth(this.loggined);
    }
}

服务:

    auth(log:boolean):boolean {
        console.log(log);
        return log;
    }

守卫:

export class AuthGuard implements CanActivate, OnInit {
  constructor(private galleryService: GalleryService) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.galleryService.auth();
  }
  ngOnInit() {

  }
}

【问题讨论】:

  • 不相关,但您可能正在寻找logged_in。在声明中赋值时也不需要设置类型。
  • guard 文件中,canActivate 函数应该返回 true 或 false。您正在从 canActivate 返回 this.galleryService.auth() 但您没有将任何参数传递给函数。
  • @nilansh 如何正确传递“guard”中变量“this.loggined”的值?
  • @IgorShvets 你可以在下面看到答案。

标签: javascript angular typescript authentication guard


【解决方案1】:

您可以创建一个服务来访问 AppComponent 和 AuthGuard 中 this.loggedIn 的值。而不是在 AppComponent 中声明 this.loggedIn 变量,而是在服务中声明它。

LoggedInService

import { Injectable } from '@angular/core';

@Injectable()
export class LoggedInService {

  constructor(
    private router:Router
  ) { }

  private loggedIn;

  setLoggedIn(data){
   // Change Value of this.loggedIn to true or false according to your logic 
  }

  getLoggedIn(){
   return this.loggedIn;
  }

}

App.component.ts

export class AppComponent implements OnInit {


  constructor(private galleryService: GalleryService,
            private loggedInService: LoggedInService
  ) {}

  ngOnInit() {
    this.logTog();
  }

  logTog(): void {
    this.loggedInService.loggedIn = !this.loggedInService.loggedIn;
    this.galleryService.auth(this.loggedInService.loggedIn);
  }
}

根据您的逻辑,身份验证文件保持不变

//相同的代码

guard.ts

export class AuthGuard implements CanActivate, OnInit {
  constructor(private galleryService: GalleryService,
              private loggedInService: LoggedInService
  ) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.galleryService.auth(this.loggedInService.loggedIn);
  }
  ngOnInit() {

  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    相关资源
    最近更新 更多