为什么不更改auth.guard中的值?

时间:2018-10-14 14:47:27

标签: javascript angular typescript authentication guard

我有一个变量body{ background-color:#fff !important; } ,我可以使用loggined方法更改其值。通过这种方法,我向服务发送了请求,并在其中传输了当前结果logTog()。在控制台中“未定义”为什么以及如何解决?

AppComponent代码:

to auth.guard

服务:

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;
    }

1 个答案:

答案 0 :(得分:0)

您可以提供服务以访问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() {

  }
}