2016-06-20 6 views
0

私はAngular2アプリで書いたサービスでObservable(ContentServiceと呼ばれる)を見ていますが、これは次のようなものです):RxJS .flatmapを使用してAngular2で観測可能な2つのストリームを結合する

@Injectable() 
export class ContentService { 

    constructor(private http:Http, private apiService:ApiService) { 

     this.content = this.http.get('src/i18n/en.json') 
      .map((res:Response) => { 
       let json: {} = res.json(); 
       return mapData(json); 
      }) 

     mapData() { 
      // function stuff to format data 
     } 

は今、私は私の注入さapiServiceに電話をしたい、これはthis.contentによって生成されたものと同じ構造を持つJSONオブジェクトを返します。 this.contentはローカルのjsonファイルに由来し、apiStreamはサードパーティのAPI/httpフィードに由来することに注意してください。 apiServiceの結果を観察可能なthis.contentに連結(または追加)する必要があります。私はflapMapがこれの最善の方法だと思っていますが、私は構文ミスを犯しています。私はそのような新しいコンテンツを追加することを考えていた

this.content = this.http.get('src/i18n/' + this.userLang + '.json') 
      .map((res:Response) => { 
       let json: {} = res.json(); 
       return mapData(json); 
      }) 
      .flatMap(() => { 
       apiService.getAllCurrentListings().subscribe(response => { 
        return mapData(response); 
       }) 
      }); 

しかし、これは間違いを明らかにしています。 .flapMapのようなAPIサービスを呼びたいのですが、私が望むデータが得られるので、私は明らかに構文エラーを作りました。元のthis.content呼び出し結果にapiServiceデータを追加するにはどうすればよいですか?

事前に感謝します。

答えて

0

this.contentが保持するはずのデータはありますか?

あなたのコードでは、this.http.getから取得でき、監視可能です。 httpデータの応答を取得するには、これを行う必要があります。それと

Injectable() 
 
export class ContentService { 
 

 
    constructor(private http:Http, private apiService:ApiService)  { 
 

 
     his.http.get('src/i18n/en.json') 
 
      .map((res:Response) => { 
 
       let json: {} = res.json(); 
 
       return mapData(json); 
 
      }) 
 
      .subscribe(mappedData => 
 
         this.content = mappedData) 
 

 
     mapData() { 
 
      // function stuff to format data 
 
     } 
 
    } 

あなたの第二のスニペットも間違っていることを想像できる、と述べました。 しかし、私はapiService.getAllCurrentListingsが最初のhttp呼び出しにデータ依存関係がないことを理解しているので、この場合はflatMap演算子を使用しません。したがって、forkJoin演算子はこのトリックを行うことができます。アレイ構造における

import {Observable} from 'rxjs/Observable' 
 

 
Observable.forkJoin([ 
 
    this.http.get('src/i18n/' + this.userLang + '.json'), 
 
    this.apiService.getAllCurrentListings()]) 
 
    .map(res => { 
 
    this.content = this.mapData(res[0].json()) 
 
    /* again, I dind't get what this.content is supposed to hold, but we need a different variable to store the second result */ 
 
    this.content2 = this.mapData(res[1].json()) 
 
    }) 
 

.forkJoin基N観測、したがって、各応答はそれに応じて配列のインデックスを使用して読み取られなければなりません。

これが必要なものでない場合は、this.contentの定義と保存する内容を入力してください。

+0

おかげで、私は実際にforkJoinで行くことにしましたapiサービス –

1

これは私が解決策として思いついたものです:私は `this.content`はいけないとして再これを開発する必要がありますが、更新のための

this.content = Observable.forkJoin(
      this.http.get('src/i18n/en.json').map((res:Response) => res.json()), 
      apiService.getAllCurrentListings() 
     ).map(res => { 
      let tempJson:{} = Object.assign(res[0], res[1]); 
      return mapData(tempJson); 
     }) 
+0

をお待ちください、これは私のためにも機能し、flatMapほど面倒ではありません – nisenish

関連する問題