Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Angular中,这是在尝试关闭可观察订阅之前检查其是否已打开的有效方法吗?_Angular_Typescript - Fatal编程技术网

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

在Angular中,这是在尝试关闭可观察订阅之前检查其是否已打开的有效方法吗?,angular,typescript,Angular,Typescript,在Angular中,这是在尝试关闭可观察订阅之前检查其是否已打开的有效方法吗?它似乎产生了正确的行为。也就是说,它只关闭打开的订阅。我想知道的是,是否有一些更“正确”的方式来做它的角度 import { Component, OnUpdate, OnDestroy } from '@angular/core'; import { AngularFirestore } from 'angularfire2/firestore'; import { VoteService } from '../..

在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();
    }

  }

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

因此,如果需要,也可以在if语句中使用它:

if (this.voteSubscription && !this.voteSubscription.closed) 
然而,这是不需要的,RxJs在内部为我们做这件事。在unsubscribe方法中,您会发现如下内容:

if (this.closed) {
      return;
    }
因此,您可以安全地调用unsubscribe,而不必担心流可能已经关闭。

您也可以使用此选项:

import {Subscriber} from 'rxjs';

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

看起来您遇到的问题不是关闭取消订阅,而是未初始化的属性。是这样吗?如果是的话,那么你的问题应该被重新表述。根据我的经验,这是不正确的。没有导致应用程序崩溃的订阅时取消订阅。它只在我确定有订阅后取消订阅时才起作用