I have a function that makes some calls to a Firebase database that aggregates a bunch of user profile data together. The one issue I'm running into is if the users don't have a videos
property on their user object, the observable errors out.
Right now, I'm checking to see if there are any videos on the user object. If there are, it returns a new observable that combines a bunch of observables based on the data that it fetches from that videos
property (an array). However, if there aren't, I need to return the original observable before the .switchMap()
.
Does anyone know what I need to tweak here?
Here's my function:
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()
}
});
}
You don't have to return the original observable, you only have to return an observable that emits the original value, as the switchMap
will be invoked when original observable re-emits. You can do that with 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);
}
});
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加