forkJoined observables不在组件中呈现输出

时间:2017-10-14 09:01:30

标签: angular angularfire2

我的所有帖子数据都位于/posts

上传新帖子时,postId也会保存在/people/${userId}/posts

拥有getFeed(uri, fetchPostDetails = false)

获取所有帖子Feed(常规Feed页面)时,它使用uri posts& false为fetchPostDetails并检索bc所有的帖子数据都在那里。

问题 在检索用户帖子和发布数据时,它将获取用户的帖子,然后单独获取该帖子数据。因此它创建了多个observable并返回一个forkJoined Observable以在Component中呈现。无法渲染它。

// located angularFireHelper  service 

getUserFeed(uri, fetchPostDetails = true) {
    let query = null;
    query = this.database.list(`/${uri}`,
        {
            query: {
                orderByKey: true,
            }
        });


    // IF not general feed fetchPostDetails
    if (fetchPostDetails) {
        return query.map((posts) => {
            console.log('User page so fetchPostDetails called');

            let source = [];
            source = posts.map(post => {
                // returns an Observable
                return this.database.object(`/posts/${post.$key}`);
            });

            return Observable.forkJoin(source);
        });
}


// userFeed.component.ts
ngOnInit() {
    this.componentName = 'user page component';
    this.user = this.afAuth.authState;
    this.getUsersFeedPosts();
}


getUsersFeedPosts() {
    this.user.subscribe(
        (value) => {
            console.log('value', value.uid);
            this.currentUser = value;
            this.afHelperService.getUserFeed(`people/${this.currentUser.uid/posts`).subscribe(
                (posts) => {
                        console.log('posts', posts);
                        this.userPosts = posts;
                    });
}


// userFeed.component.html
{{ userPosts | json }}


// In the console for posts (userPosts) it shows 

posts ForkJoinObservable {_isScalar: false, sources: Array(4), resultSelector: null}
enter code here
sources: (4) [FirebaseObjectObservable, FirebaseObjectObservable, FirebaseObjectObservable, FirebaseObjectObservable]

更新 将angularFireHelperService代码更改为以下工作。不是100%肯定为什么这是我能让它工作的唯一方法。看起来像是使用zip操作符的反模式。

if (fetchPostDetails) {
    return query.switchMap((posts) => {
        console.log('User page so fetchPostDetails called');

        let source = [];
        source = posts.map(post => {
            // returns an Observable
            return this.database.object(`/posts/${post.$key}`);
        });

            return Observable.zip(...source);
    });

1 个答案:

答案 0 :(得分:1)

您可以使用switchMap扩展您的流。更改为 query.switchMap

if (fetchPostDetails) {
        return query.switchMap((posts) => {
            console.log('User page so fetchPostDetails called');
            let source = [];
            source = posts.map(post => {
                // returns an Observable
                return this.database.object(`/posts/${post.$key}`);
            });
            return Observable.forkJoin(source);
 });