ngIf不会评估异步代码Angular和Firebase

时间:2017-09-28 02:19:41

标签: javascript angular firebase firebase-authentication

我的AuthService中有一个属性,告诉您是否登录。

export class AuthService {
  token: string;
  isLogIn = new Subject<boolean>();

当我正确登录时,另一方面当我点击注销时将isLogIn设置为true我将该属性设置为false。我的AppComponent中有这个逻辑(第一个组件被加载)。

firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        // User is signed in.
        this.authService.user = new User(user.displayName, user.email, user.photoURL, user.uid);

        console.log(user);
        this.isLoading = false;
        this.authService.isLogIn.next(true);
      } else {
        // No user is signed in.
        console.error('no user is login');
        this.authService.isLogIn.next(false);
      }
    });

在我的HeaderComponent中我有:

export class HeaderComponent implements OnInit {
  isActivated = false;
  constructor(private authService: AuthService) { }
  ngOnInit() {
    this.authService.isLogIn.asObservable().subscribe(
      (data: boolean) => {
        this.isActivated = data;
      }
    );
    // this.isActivated = this.authService.isLogin();
  }

}

模板:

<ng-template [ngIf]="!isActivated">
      <a class="nav-item nav-link text-white anchor-hover"

         routerLink="/login"
         routerLinkActive="active font-weight-bold">
        <i class="fa fa-sign-in pr-2" aria-hidden="true"></i>Ingresar
      </a>
    </ng-template>
    <ng-template [ngIf]="isActivated">
      <!--DROPDOWN PROFILE-->
      <div class="btn-group" role="group" *ngIf="authService.user">
        <button id="btnGroupDrop1" type="button" class="btn btn-light dropdown-toggle pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
          {{authService.user.displayName}}
        </button>
        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="btnGroupDrop1">
          <a class="dropdown-item" href="#">Dropdown link</a>
          <a class="dropdown-item" href="#">Dropdown link</a>
        </div>
      </div>
      <a class="nav-item nav-link text-white anchor-hover"
         routerLink="/dashboard"
         routerLinkActive="active font-weight-bold">
        <i class="fa fa-sign-in pr-2" aria-hidden="true"></i>Dashboard
      </a>
    </ng-template>

我在这里查看的是,当用户登录时,我向他显示一个仪表板按钮并隐藏登录按钮,但这只有在刷新页面或查看当前路线时才会显示。我不想更改路线或刷新页面以查看不同的UI组件,具体取决于您是否登录。

现在我告诉你整个文件: AppRouting模块:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from './shared/home/home.component';
import {LoginComponent} from './public/login/login.component';
import {DashboardComponent} from './auth/dashboard/dashboard.component';

const routes: Routes = [
  {path: '', component: HomeComponent},
  {path: 'login', component: LoginComponent},
  {path: 'dashboard', component: DashboardComponent}
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule{}

AppComponent.ts

import {Component, OnInit} from '@angular/core';
import * as firebase from 'firebase';
import {AuthService} from './public/services/auth.service';
import {User} from "./auth/models/user.model";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  isLoading = true;
  constructor(private authService: AuthService) {}

  ngOnInit() {

    // this.authService.isLogIn.next(localStorage.length > 0);

    firebase.auth().onIdTokenChanged(
      (data) => {
        console.log('TOKEN HAS CHANGED', data);
        if(data) {
          data.getIdToken().then(
            (tk) => {
              this.authService.token = tk;
            }
          );
        } else {
          console.log('You don\'t have a token yet, please login...');
          // TODO this means that the user is new or have logout.
        }
      }
    );

    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        // User is signed in.
        this.authService.user = new User(user.displayName, user.email, user.photoURL, user.uid);

        console.log(user);
        this.isLoading = false;
        this.authService.isLogIn.next(true);
      } else {
        // No user is signed in.
        console.error('no user is login');
        this.authService.isLogIn.next(false);
      }
    });

    // check localstorage, so we can see if there is a logged user
    if (this.authService.getLocalUserInfo()) {
      this.authService.isLogIn.next(true);
    } else {
      this.authService.isLogIn.next(false);
    }
  }
}

AppComponent Template:

<div>
  <app-header></app-header>
</div>


<div>
  <router-outlet></router-outlet>
</div>

AppHeader.ts

import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../public/services/auth.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  isActivated = false;
  constructor(private authService: AuthService) { }
  ngOnInit() {
    this.authService.isLogIn.asObservable().subscribe(
      (data: boolean) => {
        this.isActivated = data;
      }
    );
    // this.isActivated = this.authService.isLogin();
  }

}

AppHeader模板

<nav class="navbar navbar-expand-lg navbar-dark bg-custom-nav px-5">
  <a class="navbar-brand" routerLink="/">MovieApp</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="container-fluid">
    <div class="collapse navbar-collapse d-lg-flex justify-content-lg-between row" id="navbarNavAltMarkup">
      <div class="navbar-nav px-sm-4 px-lg-0">
        <a class="nav-item nav-link text-white"
           routerLink="/"
           routerLinkActive="active font-weight-bold"
           [routerLinkActiveOptions]="{exact: true}">Inicio</a>
      </div>
      <div class="col-lg-8">
        <app-search-bar></app-search-bar>
      </div>
      <div class="row">
        <ng-template [ngIf]="!isActivated">
          <a class="nav-item nav-link text-white anchor-hover"

             routerLink="/login"
             routerLinkActive="active font-weight-bold">
            <i class="fa fa-sign-in pr-2" aria-hidden="true"></i>Ingresar
          </a>
        </ng-template>
        <ng-template [ngIf]="isActivated">
          <!--DROPDOWN PROFILE-->
          <div class="btn-group" role="group" *ngIf="authService.user">
            <button id="btnGroupDrop1" type="button" class="btn btn-light dropdown-toggle pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
              {{authService.user.displayName}}
            </button>
            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="btnGroupDrop1">
              <a class="dropdown-item" href="#">Dropdown link</a>
              <a class="dropdown-item" href="#">Dropdown link</a>
            </div>
          </div>
          <a class="nav-item nav-link text-white anchor-hover"
             routerLink="/dashboard"
             routerLinkActive="active font-weight-bold">
            <i class="fa fa-sign-in pr-2" aria-hidden="true"></i>Dashboard
          </a>
        </ng-template>

      </div>
    </div>
  </div>
</nav>

AuthService.ts

import * as firebase from 'firebase';
import {Router} from '@angular/router';
import { Injectable } from "@angular/core";
import {Subject} from "rxjs/Subject";
import {User} from "../../auth/models/user.model";

@Injectable()
export class AuthService {
  token: string;
  isLogIn = new Subject<boolean>();
  user: User;


  constructor(private router: Router){}

  signinWithFacebook() {
    const provider = new firebase.auth.FacebookAuthProvider();
    provider.addScope('user_location');
    return firebase.auth().signInWithPopup(provider)
      .then(
        (res) => {
          console.log(res);
          this.getTokenId();
          localStorage.setItem('userInfo', JSON.stringify(firebase.auth().currentUser.providerData[0]));
          const userInfo = firebase.auth().currentUser.providerData[0];
          this.user = new User(userInfo.displayName, userInfo.email, userInfo.photoURL, userInfo.uid);

          this.isLogIn.next(true);
          this.router.navigate(['/dashboard']);
        }
      );
  }

  getTokenId() {
    firebase.auth().currentUser.getIdToken()
      .then(
        (tk) => {
          return this.token = tk;
        }
      );
  }

  logout() {
    return firebase.auth().signOut();
    // handle in component
  }

  getLocalUserInfo(): boolean {
    if(localStorage.getItem('userInfo')) {
      const transformStoredUser = JSON.parse(localStorage.getItem('userInfo'));
      this.user = new User(transformStoredUser.displayName, transformStoredUser.email, transformStoredUser.photoURL, transformStoredUser.uid);
      return true;
    } else {
      return false;
    }
  }
  isLogin():boolean {
    if (localStorage.getItem('userInfo')) {
      return true;
    }
    return false;
  }
}

您可以在https://github.com/lucasdavidferrero/movieApp找到完整的项目 还有一件事,我使用了异步管道,但模板并没有反映出这些特征。在github项目中,您会发现我在模板中使用异步但仍然是同一个bug。我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:2)

我将尝试帮助/回答,请注意,有很多代码要筛选,所以我可能错过了一些明显的东西。无论如何,希望能够完成代码并指向正确的方向,您可能需要查看AsyncPipe。

我想首先修改您的AuthService,以便通过首先将isLogIn = new Subject<boolean>();更改为private _isLogIn = new Subject<boolean>();来实现一些更好的做法。我们不想将Subject分享给其他会修改它的组件,所以我们的AuthService中你只需要添加下划线......最后要导出我们要使用的Subject我们可以添加这样的get函数:

get isLogIn(): Observable<boolean> {
   return this._isLogIn.asObservable();
}

现在我们不需要将asObservable()链接到我们使用它的地方。

此外,我们还希望将用户状态的变化从AppComponent移动到您的AuthService。然后,您可以在AppModule的构造函数中实例化该服务,这样一旦您的应用程序启动,您的服务就会开始监视身份验证状态的变化。

你也可能遇到一个问题,即auth状态的解析可能会超出区域,所以虽然这可能没有必要,你可以/应该从核心导入NgZone并将其传递给你的构造函数您的AuthService constructor(private router: Router, private _zone: NgZone) { }所以当您更新auth状态的值时,您可以将其包装在此函数中:

this._zone.run(() => { 
    // your code here
}

现在如果我要写你的header.component.ts,我会做这样的事情:

export class HeaderComponent implements OnInit {
  constructor(private authService: AuthService) { }

  ngOnInit() {}

  get isActivated(): Observable<boolean> {
    return this.authService.isLogIn;
  }
}

所以在这里我只是通过get函数将observable直接传递给我们的模板。所以在模板中我会像这样实现AsyncPipe:

<div *ngIf="!(isActivated | async) else user">
   <a class="nav-item nav-link text-white anchor-hover" routerLink="/login"
     routerLinkActive="active font-weight-bold">
    <i class="fa fa-sign-in pr-2" aria-hidden="true"></i>Ingresar
  </a>
</div>
<ng-template #user>
  <!--DROPDOWN PROFILE-->
  <div class="btn-group" role="group" *ngIf="authService.user">
    <button id="btnGroupDrop1" type="button" class="btn btn-light dropdown-toggle pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
      {{authService.user.displayName}}
    </button>
    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="btnGroupDrop1">
      <a class="dropdown-item" href="#">Dropdown link</a>
      <a class="dropdown-item" href="#">Dropdown link</a>
    </div>
  </div>
  <a class="nav-item nav-link text-white anchor-hover"
     routerLink="/dashboard"
     routerLinkActive="active font-weight-bold">
    <i class="fa fa-sign-in pr-2" aria-hidden="true"></i>Dashboard
  </a>
</ng-template>

AsyncPipe将自动订阅和取消订阅您的Observable并处理刷新/区域更新。

现在我给出了一些概述/基本的更改,以确保代码按预期运行。我邀请您试一试,看看您的*ngIf是否更“整洁”。但是你可能还想查看Angular中的其他内容... =&gt; https://stackoverflow.com/a/43006589/5076023