ngIf 在表达式更改时不计算表达式。角和火基



首先,我将isloading属性设置为" true",因此该元素尚未加载。(这发生在AppComponent上)

  export class AppComponent implements OnInit {
  isLoading = true;
  constructor(private authService: AuthService) {}
 .
 .
 .

bellow在ngoninit挂钩中:

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

此代码是一个异步的代码,我希望用户等待检查他是否登录,以便我可以更改标头UI。此外,我还有另一个包裹标头的组件。我用 *ngif = isloading

在AppComponent中称其为
<div>
  <app-header *ngIf="!isLoading"></app-header>
</div>

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

问题是,当isloading将其值更改为false时,我从未见过Appheader呈现。那么,为什么 *ngif不再次评估该属性?

在这里我的authservice:

import * as firebase from 'firebase';
// import {User} from "../../auth/models/user.model";
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;
  }
}

appheader.ts

import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../public/services/auth.service';
import * as  firebase from 'firebase';
import {User} from "../../auth/models/user.model";
import {Observable} from "rxjs/Observable";
@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,

isLogIn = new BehaviorSubject(false);
// add a getter
get isLogin() {
 return this.isLogIn;
}

然后在模板中,

<app-header *ngIf="authService.isLogin | async"></app-header>

最新更新