可观察到的混乱 [英] Observable Confusion
问题描述
我正在使用 Ionic2
和 AngularFire2
.
我也在使用 rxjs
Observable
.我有以下代码:
I am also making use of a rxjs
Observable
. I have the following code:
findChatsForUid(uid: string): Observable<any[]> {
return this.af.database.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
}).map(items => {
const filtered = items.filter(
item => (item.memberId1 === uid || item.memberId2 === uid)
);
return filtered;
});
}
和
deleteChatsAndMessagesForUid(uid: string): Promise<any> {
return new Promise<any>((resolve) => {
let promiseArray: Promise<any>[] = [];
this.findChatsForUid(uid).map(items => {
return items;
}).forEach((chatItems) => {
for (let i: number = 0; i < chatItems.length; i++) {
promiseArray.push(this.deleteChat(chatItems[i], true));
}
Promise.all(promiseArray).then(() => {
resolve(true);
});
});
});
}
在第二个函数中,您可以看到我从第一个函数中检索了 Observable
,并使用 forEach
函数循环遍历每个项目.
In the second function, you can see I retrieve the Observable
from the first, and the loop through each item using the forEach
function.
我的问题是,因为这是一个 Observable
,所以总是有对象的句柄.因此,当我执行以下操作时:
My problem is, because this is an Observable
, there is always a handle to the object. So when I do the following:
deleteChatsAndMessagesForUid(uid).then(() => {
user.delete().then(() => {
...
}
}
它导致以下错误,因为被删除的用户仍在尝试观察Observable
.
It results in the following error because the deleted user is still trying to observe the Observable
.
错误:未捕获(承诺):错误:permission_denied at/chat:客户无权访问所需数据.错误:permission_denied at/chat: 客户端无权访问所需的数据.
Error: Uncaught (in promise): Error: permission_denied at /chat: Client doesn't have permission to access the desired data. Error: permission_denied at /chat: Client doesn't have permission to access the desired data.
问题
有没有办法检索数据,而无需仍然附加到 Observable
上?这样我就可以随意删除关联用户了?或者有没有更好的方法来处理这个问题?
Is there a way to retrieve the data, without still being attached to the Observable
? So that I am free to delete the associated user? Or is there a better way to handle this?
谢谢
推荐答案
听起来您想在第一个发出的列表之后从 list
observable 中取消订阅.
It sounds like you want to unsubsribe from the list
observable after the first emitted list.
您可以使用 first
运算符在第一个发出的列表之后完成 list
observable.这将导致自动取消订阅,并且侦听器将从内部 Firebase 引用中删除.
You can use the first
operator to complete the list
observable after the first emitted list. This will result in automatic unsubscription and the listeners will be removed from the internal Firebase ref.
import 'rxjs/add/operator/first';
findChatsForUid(uid: string): Observable<any[]> {
return this.af.database
.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
})
.first()
.map(items => {
const filtered = items.filter(
item => (item.memberId1 === uid || item.memberId2 === uid)
);
return filtered;
});
}
这篇关于可观察到的混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!