在Angular中,这是在尝试关闭可观察的订阅之前将其检查是否有效的有效方法吗?

时间:2018-08-25 06:42:18

标签: angular typescript

在Angular中,这是在尝试关闭可观察的订阅之前是否对其进行检查的有效方法?它似乎产生正确的行为。也就是说,它仅关闭打开的订阅。我想知道的是,在Angular中是否还有其他“正确”的方法。

import { Component, OnUpdate, OnDestroy } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { VoteService } from '../../services/vote.service';

export class Foo implements OnUpdate, OnDestroy {

  private voteSubscription;

  constructor(private afs: AngularFirestore,public voteService: VoteService) {}

  ngOnUpdate() {

    /* Lots of complicated things happen here which result in voteSubscription
       being opened and closed based on external conditions including but not
       limited to auth state. Bottom line is that sometimes the subscription
       is active and sometimes it's not. */

       if ( CONSTANTLY_CHANGING_INPUT_CONDITIONS ) {
          this.voteSubscription = this.voteService.getUserVotes().subscribe();
        } else {
          if (this.voteSubscription) {
            this.voteSubscription.unsubscribe();
          }
        }

  }

  ngOnDestroy() {

    /* Avoid producing a console error if we try to close a subscription that is
       already closed. */
    if (this.voteSubscription) {
      this.voteSubscription.unsubscribe();
    }

  }

}

2 个答案:

答案 0 :(得分:3)

Subscription 对象还具有一个 closed 属性,可用于检查流是否已取消订阅(完成或发生错误)。

因此,如果您愿意,也可以在if语句中使用它:

if (this.voteSubscription && !this.voteSubscription.closed) 

但是不需要,RxJs在内部为我们执行此操作。在取消订阅方法中,您会发现类似以下内容:

if (this.closed) {
      return;
    }

因此,人们可以放心地取消订阅,而不必担心流可能已经关闭。

答案 1 :(得分:1)

您也可以使用它:

import {Subscriber} from 'rxjs';

this.voteSubscription instanceof Subscriber // returns true if is a subscriber