如何从订阅中返回一个observable以便订阅?

时间:2016-11-12 22:07:09

标签: angular typescript rxjs observable

我的想法是这样做:

getCast(id:number, numCast:number){
        return this.getCredits(id)
            .map( credits => credits.cast.length >= numCast ? credits.cast.slice(0,numCast) : credits.cast )
            .subscribe(character => {
                for(let index in character){
                    return this.getPerson(character[index].id);
                }
            });
    }

getPerson(person_id:number) {
    return this.http.get('https://api.themoviedb.org/3/person/'+person_id+'?'+this.apiKey)
                    .map(data => JSON.parse(data['_body']))
}

this.mvs.getCast(this.route.snapshot.params['id'], 6)
        .subscribe( data => { console.log(data); })

但它根本不起作用。 控制台中的错误说:

_this.mvs.getCast(...).subscribe is not a function

1 个答案:

答案 0 :(得分:0)

这里的问题是你要两次订阅getCast(内部和外部)。这样的事情应该有效:

从电影中获取演员

getCast(id:number, numCast:number) {
  return this.getCredits(id)
    .map(credits => credits.cast.length >= numCast ? credits.cast.slice(0,numCast) : credits.cast );
}

订阅getCast并获取所有演员

this.mvs.getCast(this.route.snapshot.params['id'], 6)
  .subscribe(character => {
    for(let index in character) {
      return this.getPerson(character[index].id);
    }
  })

然后,订阅getPerson以显示演员的数据

getPerson(person_id: number) {
  return this.http.get(`https://api.themoviedb.org/3/person/${person_id}?${this.apiKey}`)
    .map(data => JSON.parse(data['_body']))
    .subcribe(actor => this.actor = actor);
}