Observable Confusion

谁都会走 提交于 2019-12-12 18:28:18

问题


I am using Ionic2 with AngularFire2.

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

and

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

In the second function, you can see I retrieve the Observable from the first, and the loop through each item using the forEach function.

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(() => {
        ...
    }
}

It results in the following error because the deleted user is still trying to observe the Observable.

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.

Question

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?

Thanks


回答1:


It sounds like you want to unsubsribe from the list observable after the first emitted list.

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


来源:https://stackoverflow.com/questions/42851369/observable-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!