1

我正在使用 angular-cli 构建一个 angularfire2 应用程序。

我遇到了一个问题,在初始子子路由加载时,angularfire2 在控制台中引发错误:

error_handler.js:47 例外:未捕获(承诺):TypeError:无法读取未定义的属性“订阅”

当我的页面“刷新”时会发生这种情况。如果我离开组件并在刷新后返回它,数据加载得很好,我没有收到错误。我不确定这是否是 Angular2、AngularFire2 的错误,或者我做错了什么。有人遇到过这个问题吗?这是我的相关组件代码:

import {Component, OnInit, ViewChild, OnDestroy}from '@angular/core';
import {Router} from '@angular/router';
import {AngularFire, FirebaseListObservable, AngularFireModule} from 'angularfire2';


@Component({
  selector: 'app-users',
  templateUrl: 'users.component.html',
  styleUrls: ['users.component.scss', '../shared/styles/dashboard.scss']
})
export class EmployeesComponent implements OnInit, OnDestroy {
  private groupKey: string;
  private groupAdmin: string;
  private user: any;
  private _auth: any;

  private positions: FirebaseListObservable < any > ;
  private users: FirebaseListObservable < any > ;

  constructor(private af: AngularFire, private router: Router) {}

  ngOnInit() {
    this.af.auth.subscribe(auth => {
      this._auth = auth;
      let currentUser = this.af.database.object('/Users/' + this._auth.uid).take(1).subscribe(user => {
        this.groupKey = user.group;
        this.users = this.af.database.list('/Users', {
          query: {
            orderByChild: 'group',
            equalTo: this.groupKey
          }
        });
        this.positions = this.af.database.list('/Groups/' + this.groupKey + '/Positions');
        this.af.database.object('/Groups/' + this.groupKey + '/admin').take(1).subscribe(group => {
          this.groupAdmin = group.admin;
        });
      });
    });
  }



  ngOnDestroy() {
    this.users.subscribe().unsubscribe();
    this.positions.subscribe().unsubscribe();
  }

}

4

1 回答 1

3

您必须重构您的ngOnDestroy方法,因为它是错误的,首先,如果您async在模板中使用管道,则不需要取消订阅,如果不取消订阅,则在您的内部您ngOnInit应该unsubscribe为每个subscription调用保存对函数的引用,然后调用它们on ngOnDestroy你可以在这里阅读更多关于它的信息)

于 2016-11-22T22:21:19.373 回答