2017-01-26 3 views
2

私はFirebaseデータベースを呼び出し、いくつかのユーザプロファイルデータをまとめて収集する機能を持っています。私が取り組んでいる1つの問題は、ユーザが自分のユーザオブジェクトにvideosプロパティを持たず、観測可能なエラーが出てしまうことです。Angular 2 Observables - switchMap/combineLatestの代わりに元の観測値を返す

今、ユーザーオブジェクトに動画があるかどうかを確認しています。存在する場合、それは、そのvideosプロパティ(配列)からフェッチするデータに基づいて一連のオブザーバブルを組み合わせた新しいオブザーバブルを返します。しかし、もし存在しなければ、私は.switchMap()の前に元の観察可能なものを返す必要があります。

誰も私がここで微調整する必要があることを知っていますか?ここで

は私の機能です:

getUserProfile(id) { 
    return this._af.database 
     .object(`/social/users/${id}`) 

     // Switch to the joined observable 

     .switchMap((user) => { 

     let vidKeys = Object.keys(user.videos); 

     if(vidKeys && vidKeys.length > 0) { 
      // Use forkJoin to join the video observables. The observables will 
      // need to complete, so first is used. And use forkJoin's selector to 
      // map the videos to the user and then return the user. 

      return Observable.combineLatest(
      vidKeys.map((vidKey) => this._af.database 
       .object(`/social/videos/${vidKey}`) 
      ), 
      (...videos) => { 
       vidKeys.forEach((vidKey, index) => { 

       // Query YouTube api to get the duration 
       this._yt.getVideo(vidKey).subscribe(data => { 

        // Format the duration 
        let duration = this._yt.convertToStandardDuration(data.items[0].contentDetails.duration) 
        videos[index]['duration'] = duration; 
        user.videos[vidKey] = videos[index]; 

       }); 

       }); 
       return user; 
      } 
     ) 
     } else { 

      // TO-DO: Return original observable that was called before the .switchMap() 

     } 
     }); 
    } 

答えて

2

あなたが元に観察を返す必要はありません、あなただけの時に元に観察switchMapが呼び出されるように、元の値を発すること、観察を返す必要が再発光する。あなたはObservable.ofでそれをすることができます:

import 'rxjs/add/observable/of'; 

getUserProfile(id) { 
    return this._af.database 
    .object(`/social/users/${id}`) 
    .switchMap((user) => { 

     let vidKeys = Object.keys(user.videos); 

     if(vidKeys && vidKeys.length > 0) { 
     ... 
     } else { 
     return Observable.of(user); 
     } 
    }); 
} 
+0

あなたはもう一度私を保存します。実際にコールが完了するかどうかを確認するために、私は実際に 'Observable.of([])を返す 'のようなものを試していたと思いますか? :) 再度、感謝します。乾杯! –

関連する問題