Observable Confusion

2019-07-12 22:09发布

问题:

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