角度分量之间共享变量

时间:2020-03-12 15:18:19

标签: angular

我正在尝试在两个独立组件之间共享变量。

在刷新页面之前,一切正常,注销按钮消失。 我共享变量是为了显示或隐藏此按钮(在用户连接时显示)

当我使用ngAfterViewChecked时,它可以工作,但是我发现这不是一个好习惯。

login.service.ts

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  private isLoggedIn = new Subject<boolean>();

  getIsLoggedIn(): Observable<boolean> {
    if (localStorage.getItem('token') != null) {
      this.updateIsLoggedIn(true);
      return this.isLoggedIn.asObservable();
    }else{

      return this.isLoggedIn.asObservable();
    }
 }

  updateIsLoggedIn(state: boolean) {
   this.isLoggedIn.next(state);
 }

单击登录按钮时将执行以下方法

login.component.ts

login(AuthenticationRequest){
    this.loginService.login(AuthenticationRequest).subscribe(
      res => {
        console.log(res);
        localStorage.setItem('token',res.jwt);
        this.router.navigate(['patient/calendrier']);
        this.incorrect = false;
        this.loginService.updateIsLoggedIn(true);

      }, error => {
        console.log(error);
        this.incorrect = true;
      }
    )
  }

header.component.ts

export class HeaderComponent implements OnInit {

  subscription;
  isLoggedIn: boolean = false;

constructor(private router: Router, private loginService: LoginService) {

  }

  ngOnInit() {
    this.today = new Date();
    this.subscription = this.loginService.getIsLoggedIn().subscribe(
      state => { this.isLoggedIn = state;
      }
    )
  }


  logout() {
    console.log();
    localStorage.removeItem("token");
    this.loginService.updateIsLoggedIn(false);
    location.reload();

  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

header.component.html

...
<button *ngIf="isLoggedIn"  nz-button (click)="logout()">Se déconnecter</button>
...

1 个答案:

答案 0 :(得分:1)

我想说sessionStorage更适合处理用户会话。在验证令牌的情况下,它也可以很好地帮助您测试其有效性。请尝试以下操作:

login.service.ts

import { distinctUntilChanged } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  private isLoggedInSource = new BehaviorSubject<boolean>(false);
  private isLoggedIn$ = this.isLoggedInSource.asObservable().distinctUntilChanged();

  public getIsLoggedIn(): Observable<boolean> {
    if (tokenValid()) {
      this.updateIsLoggedIn(true);
    }
    return this.isLoggedIn$;
  }

  public updateIsLoggedIn(state: boolean) {
   this.isLoggedInSource.next(state);
  }

  private tokenValid(): boolean {
    let result = false;
    const token = sessionStorage.getItem('token')
    if (token !== null) {
      const exp = (JSON.parse(atob(token.split('.')[1]))).exp;
      if ((Math.floor((new Date).getTime() / 1000)) < exp) {
        result = true;
      }
    }
    return result;
  }
}

distinctUntilChanged运算符避免推送冗余值。

login.component.ts

login(AuthenticationRequest) {
  this.loginService.login(AuthenticationRequest).subscribe(
    res => {
      sessionStorage.setItem('token', res.jwt);
      this.router.navigate(['patient/calendrier']);
      this.incorrect = false;
      this.loginService.updateIsLoggedIn(true);
    }, 
    error => {
      this.incorrect = true;
    }
  );
}

header.component.ts

export class HeaderComponent implements OnInit {
  private subscription;
  private isLoggedIn: boolean;

  constructor(private router: Router, private loginService: LoginService) { }

  ngOnInit() {
    this.today = new Date();
    this.subscription = this.loginService.getIsLoggedIn().subscribe(
      state => { this.isLoggedIn = state; }
    );
  }

  private logout() {
    sessionStorage.removeItem("token");
    this.loginService.updateIsLoggedIn(false);
    location.reload();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

header.component.html

<button *ngIf="isLoggedIn"  nz-button (click)="logout()">Se déconnecter</button>