在angular2 rxjs

时间:2017-05-25 17:58:45

标签: javascript angular http rxjs observable

我是angular 2的新手,想要进行嵌套的http调用,其中一个调用依赖于下一个调用。我的代码在服务中如下:

getUserPosts(): Observable<any[]>{
    return this.http.get(this.apiUserURL + this.userId + '/')
        .map((response: Response)  => response.json())  
        .flatMap((users) => {
            return Observable.forkJoin(
                users.map(user=>
                    this.http.get(this.apiUserPostURL + user.id)
                    .flatMap(response => response.json())   
                )   
            )
        })
}

在我有的组件中:

ngOnInit() {
this.results = this.postsService.getUserPosts()
  .subscribe(posts => {  this.posts = posts
    console.log(posts);
  })   

}

当我这样做时,我得到每个用户的最后一篇帖子,但不是所有帖子。 (我的每个用户都有3个帖子,我的数据库中有两个用户,但在下面我只收到每个用户的一个帖子:

(2)[对象,对象] 0:对象 1:对象

预计

解决方案:获取所有用户的所有帖子,如下所示:    (6)[对象,对象,对象,对象,对象,对象]

当我将服务的最后一部分更改为以下内容时:

users.map(user=>
    this.http.get(this.apiUserPostURL + user.id)
    .map(response => response.json())   
)   

我得到两个阵列,每个3个帖子,我不知道如何使用* ngFor访问这些帖子:

(2)[Array(3),Array(3)] 0:阵列(3)   0:对象   1:对象   2:对象 1:阵列(3)   0:对象   1:对象   2:对象

预期的解决方案:直接与数组联系,而不是每个用户都有一个对象数组,而是一个包含所有对象的数组:    (6)[对象,对象,对象,对象,对象,对象]

我甚至试图通过将.flatMap添加到我的组件来做其他事情,我认为会有所帮助,如下所示:

ngOnInit() {
this.results = this.postsService.getUserPosts()
 .flatMap(posts => this.posts = posts)
  .subscribe(posts => {  this.posts = posts
    console.log(posts);
  })    

}

但我有两个独立的数组,每个数组都与每个用户的所有帖子相关,* ng只选择最新用户并忽略其他用户的其他帖子:

(3)[对象,对象,对象]    0:对象    1:对象    2:对象 (3)[对象,对象,对象]    0:对象    1:对象    2:对象

预期的解决方案:将两个数组合并为一个数组:    (6)[对象,对象,对象,对象,对象,对象]

任何人都可以帮忙找出解决这个问题的方法吗? 非常感谢!!

1 个答案:

答案 0 :(得分:0)

感谢Julia Passynkova的回答让我解决了我的问题。这是最后一个解决方案,将最后一行concat.apply()添加到我的服务中:

getUserPosts(): Observable<any[]>{
return this.http.get(this.apiUserURL + this.userId + '/')
    .map((response: Response)  => response.json())  
    .flatMap((users) => {
        return Observable.forkJoin(
            users.map(user=>
                this.http.get(this.apiUserPostURL + user.id)
                .flatMap(response => response.json())   
            )   
        )
    }).map(x=> [].concat.apply([],x))

}