Der*_*ler 5 typescript angular
在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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
该认购对象也有一个封闭的特性,人们可以用它来检查,如果流已经退订(完成或有错误)。
因此,如果需要,也可以在if语句中使用它:
if (this.voteSubscription && !this.voteSubscription.closed)
Run Code Online (Sandbox Code Playgroud)
但是,这不是必需的,RxJs在内部为我们执行此操作。在unsubscribe方法中,您会发现类似以下内容:
if (this.closed) {
return;
}
Run Code Online (Sandbox Code Playgroud)
因此,人们可以放心地取消订阅,而不必担心流可能已经关闭。
| 归档时间: |
|
| 查看次数: |
2159 次 |
| 最近记录: |