Angular2& AngularFire2 - 无法读取属性' auth'为null

时间:2017-04-06 17:31:07

标签: javascript angular angularfire2

组件:

import { Component, OnInit } from '@angular/core';
import { AngularFire, FirebaseObjectObservable } from 'angularfire2';
import { Router } from '@angular/router';

@Component({
  selector: 'app-header',
  templateUrl: './app-header.component.html',
  styleUrls: ['./app-header.component.css']
})

export class AppHeaderComponent implements OnInit {
  isLoggedIn: any;
  userEmail: any;
  email: string;
  item: FirebaseObjectObservable<any>;

  constructor(public af: AngularFire, private router: Router) {
    var auth = this.af.auth.subscribe( (user) => {
      if (user) {
        this.isLoggedIn = true;
        this.userEmail = this.af.auth.subscribe(auth => {
          this.email = auth.auth.email;
          this.item = af.database.object('/users/'+ auth.auth.uid);
          console.log(this.email);
        });
      } else {
        this.isLoggedIn = false;
      }
    });

  }

  logout() {
    this.af.auth.logout();
    this.router.navigate(['login']);
  }

  ngOnInit() {

  }

}

一切正常,但是当调用logout()函数时,我在控制台中收到以下错误,我似乎无法修复它:

TypeError: Cannot read property 'auth' of null

据我所知,没有什么可以破解的,但我学习所有这一切并不是很新,并希望尽可能地清理我的代码。谢谢。

编辑:添加HTML

<nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#containerNavbar" aria-controls="containerNavbar" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item"
          [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
        <a class="nav-link" routerLink="/">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item"
          [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
        <a class="nav-link" routerLink="/about">About</a>
      </li>
    </ul>
    <div class="">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item"
            [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
          <a class="nav-link" routerLink="/login" *ngIf="!isLoggedIn">Login</a>
        </li>
        <li class="nav-item"
            [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
          <a class="nav-link" routerLink="/register" *ngIf="!isLoggedIn">Register</a>
        </li>
        <li class="nav-item dropdown" *ngIf="isLoggedIn">
          <a class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            {{ (item | async)?.battleTag }}
          </a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            <a class="dropdown-item" routerLink="/profile">Profile</a>
            <a class="dropdown-item">Settings</a>
            <a class="dropdown-item" (click)="logoutModal.show()">Logout</a>
          </div>
        </li>
      </ul>
    </div>
  </div>
</nav>

<div class="modal fade" bsModal #logoutModal="bs-modal" [config]="{backdrop: 'static'}"
     tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Logout</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close" (click)="logoutModal.hide()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Are you sure you want to logout?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" (click)="logout();logoutModal.hide()">Logout</button>
        <button type="button" class="btn btn-secondary" (click)="logoutModal.hide()">Cancel</button>
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

您需要取消订阅firebase auth以避免此错误。

import { Subscription } from 'rx/js';

export class AppHeaderComponent implements OnInit {

authSubscription: Subscription;

  onInit() {
     this.authSubscription = this.af.auth.subscribe( (user) => {
     ....
  }

  logout() {
    this.af.auth.logout();
    this.router.navigate(['login']);
    this.authSubscription.unsubscribe();
  }
}

P.S。取消订阅OnDestroy()生命周期钩子中的所有订阅是一个很好的习惯。