Angular 2 Observables - 在运行Observable之前需要等到操作完成

时间:2017-01-23 15:20:03

标签: angular firebase firebase-realtime-database ionic2

我一直在慢慢看到可观察的东西,虽然Firebase似乎要求你用它们做很多疯狂的事情才能取得成果:P基本上,我有一个功能我可以过滤掉一些密钥,基于某些条件,以便创建从我的Firebase数据库中获取的用户数组。

然而,Observable在我的过滤功能能够完成之前运行,所以我遇到了竞争条件。我的功能有点复杂(至少对我来说),所以我不确定我能做些什么来确保userKeys调用之前Observable.combineLatest是最新的:

getUsersForConversations(conversations) {
    conversations.forEach((conversation, index) => {

      // Get user out of local storage
      this.storage.get('user').then(user => {

        // Iterate through the users and remove the current user
        // to prevent an unecessary call being made
        let userKeys = Object.keys(conversation.users);

        userKeys.forEach((key, index) => {
          if(key === user.id) {
            userKeys.splice(index, 1);
          } else {

            if(userKeys.length > 0) {

              // Grab the conversation for this user and determine
              // If the conversation has been removed before
              this._af.database
              .object(`/social/conversations_last_deleted/${conversation.$key}/${user.id}`)
              .subscribe(lastDeleted => {

                if(lastDeleted && (lastDeleted.$value !== null)) {
                  this._messages.getMessagesForConvo(conversation.$key, lastDeleted).subscribe(messages => {

                    if(messages.length === 0) {
                      userKeys.splice(index, 1); // This is updated after the Observable.combineLatest :(
                    }
                  })
                };
              });
            }
          }
        });

        // Get all the users based on this list and shove them
        // into the correct conversation

        Observable.combineLatest(
          userKeys.map((userKey) => this._af.database
            .object(`/social/users/${userKey}`)
          )
        ).subscribe(users => {
          conversations[index].users = users;
          this.conversations = conversations;
        })
      });
    });
  }

有没有人有任何想法?

1 个答案:

答案 0 :(得分:0)

我试着在Observable中做所有的逻辑,请试一试,记住你必须取消订阅观察者!!

@foreach ($categories as $category)
    <tr data-id="{{ $category->id }}">
        <td>{{ $category->id }}</td>
        <td>{{ $category->name }}</td>
        <td id="actions">
            <a href="{{ url('admin/category/' . $category->id . '/get') }}">Show</a>
            <a href="{{ url('admin/category/' . $category->id . '/edit') }}">Edit</a>
            <a href="#" data-toggle="modal" data-target="#confirmDeleteModal">Delete</a>
            <confirm-delete-modal item="category" id="{{ $category->id }}" name="{{ $category->name }}"></confirm-delete-modal>
        </td>
    </tr>
@endforeach