如何在Angular2中触发一个应用范围的事件或者观察一个全局变量?

How can I fire an app-wide event in Angular2 or observe a global variable

本文关键字:一个 事件 或者 观察 全局变量 范围 应用 Angular2      更新时间:2023-09-26

我有以下架构:

导航栏是一个组件,具有:

loggedIn = false;
  constructor(private authService: AuthService) {
    this.loggedIn = authService.isAuthenticated();
  }

根据变量

显示不同的链接

authService:

中的方法
  isAuthenticated() : boolean {
    return tokenNotExpired();
  }
  authenticate(email: string, password: string) : Promise<void> {
    const headers = new Headers({
    'Content-Type': 'application/json'});
    const body = JSON.stringify({ email, password });
    return this.http.post(`${apiUrl}/auth/login`, body, { headers })
      .toPromise()
      .then(response => {
        const data = response.json();
        this.user = data.user;
        localStorage.setItem('id_token',data.token);
      });
  }

当isAuthenticated()返回另一个值时,我想在导航栏中得到通知。

我应该在AuthService中使用一个可观察的值,而不是仅仅检查有效的令牌吗?我应该在验证方法成功时发出一个事件吗?我只能找到关于@input的亲子事件发射器的信息。

注意:我使用angular2-jwt和isAuthenticated()方法是从auth调用的。保护受保护的路由

你绝对应该在你的AuthService中使用Observable主题。看看angular.io

中的链接