如何在Angular2中退订Firebase列表? [英] How do I unsubscribe from a Firebase list in Angular2?

查看:67
本文介绍了如何在Angular2中退订Firebase列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用连接到Firebase列表

I am connecting to a Firebase list using

tasks: FirebaseListObservable<ITask[]>;

constructor(private af: AngularFire) {
  this.tasks = this.af.database.list("/tasks");
}

现在我想在用户注销时取消该连接.

And now I want to cancel that connection, when my users logout.

我已经尝试过this.tasks.unsubscribe(),但是该方法似乎未定义(我尝试了此操作,因为FirebaseListObservable是可观察的).

I already tried this.tasks.unsubscribe(), but looks like the method is undefined (I tried this because FirebaseListObservable is an observable).

我也按照文档中的建议尝试了this.tasks.off(),但是它也是未定义的.

I also tried this.tasks.off() as suggested in the documentation, but it is also undefined.

最后,我尝试了this.tasks = null,并且可以使用,但是我不确定这是否是正确的实现.

Finally, I tried this.tasks = null and that works, but I'm not sure if that is the correct implementation.

推荐答案

this.tasks可观察不是订阅这就是为什么您不能退订的原因.

this.tasks is an Observable not a Subscription which is why you cannot unsubscribe.

如果您手动订阅,则可以:

If you are manually subscribing then you can:

let observable = Rx.Observable.interval(1000);
let subscription = observable.subscribe(x => console.log(x));
subscription.unsubscribe();

如果您使用的是异步管道然后,当组件销毁时,Angular将自动退订.基于源代码,如果管道的值更改为null,那么可观察对象将被取消订阅,但这在文档的任何地方均未指定.我认为一个更好的选择是显式销毁使用异步管道的组件.

If you are using the async pipe then Angular will automatically unsubscribe when the component is destroyed. Based on the source code, the observable will be unsubscribed if the value of the pipe changes to null, but this is not specified in the docs anywhere. I think a better option would be to explicitly destroy the components where you use the async pipe.

这篇关于如何在Angular2中退订Firebase列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆