2016-04-19 13 views
13

の成功を呼び出します。角度2:二つのバックエンドサービスは、私は以下のようにバックエンドサービスを持っている私の角度2のアプリで最初のサービス

getUserInterests() { 
    return this.http.get('http://localhost:8080/test/selections').map((res: Response) => res.json()); 
} 

このサービスを呼び出した後、前のサービスが成功したら別のサービスを呼び出したいと思います。

第二サービス

let params: URLSearchParams = new URLSearchParams(); 
    params.set('access_token', localStorage.getItem('access_token')); 
    return this.http.get('http://localhost:8080/user/selections', { search: params }).map((res: Response) => res.json()); 

これら2つのサービスは、個別に2つのJSON配列を返します。次に、これらの2つの配列でログインする必要があります。

EDITED

service.ts

getUserInterests() { 
    return this.http.get('http://localhost:8080/test/selections').map((res: Response) => res.json()); 
} 

getSavedSelections() { 
    let params: URLSearchParams = new URLSearchParams(); 
    params.set('access_token', localStorage.getItem('access_token')); 
    return this.http.get('http://localhost:8080/interest/user/selections', { search: params }).map((res: Response) => res.json()); 
} 

getSelectionList() { 
    var obs = this.getUserInterests().flatMap(
     (interests) => { 
      return Observable.forkJoin([ 
       Observable.of(interests), 
       this.getSavedSelections() 
      ]); 
     } 
    ); 
    return obs; 
} 

それから私は、サービスを呼び出すために、TS私の他のファイルに次のように使用しています。

export class InterestsComponent { 
    private interests; 
    private saved_interests; 
    constructor(private dataService: DataService) { 
    this.dataService.getSelectionList().subscribe(
     (result) => { 
      var interests = result[0]; 
      var selections = result[1]; 
     } 
    ); 
    } 
} 

ただし、これはコンソールログで次のエラーが発生します。

ORIGINAL EXCEPTION: TypeError: this.dataService.getSelectionList is not a function 

いずれかの提案があります。

this.service.getUserInterests().flatMap(
    (interests) => { 
    let params: URLSearchParams = new URLSearchParams(); 
    params.set('access_token', localStorage.getItem('access_token')); 
    return this.http.get('http://localhost:8080/user/selections', { 
     search: params 
    }).map((res: Response) => res.json()); 
    } 
); 

このデータフローに加入して、あなただけの最後の要求の結果を受信します:

答えて

17

あなたは完成前のものの後に1つのリクエストを呼び出すためにflatMapオペレータを活用する必要があります。

あなたは両方を返すようにObservable.forkJoinメソッドを使用することができます。ここではサンプルです:

var obs = this.service.getUserInterests().flatMap(
    (interests) => { 
    return Observable.forkJoin([ 
     Observable.of(interests), 
     this.service.getUserSelections() 
    ]); 
    } 
); 

obs.subscribe(
    (result) => { 
    var interests = result[0]; 
    var selections = result[1]; 
    } 
); 
+0

利益は何か? – Rose18

+0

2つのサービスの応答を取得するにはどうすればよいですか? – Rose18

+0

「関心」は第1の要求の結果に対応する。 –

関連する問題