2016-04-06 14 views
1

私はAngular2とrxjsを使用しています。最初に成功したときにRxJSが2番目の操作を呼び出す

login()という操作があります。これはhttp.post要求を使用して認証の詳細をサーバーに送信し、トークンを戻します。

結果を読み取る必要があります。トークンが正常に受信された場合、トークンを検証してデコードするいくつかの操作を行い、すべてがOKならトークンからサーバーにユーザー名を送信しますhttp.getを呼び出し、ユーザーの詳細を取得します。

上記のすべてをObservableとして戻したいと思いますが、RxJSを使用して2つの操作がどのように構成されるべきかについて頭を悩ませています。

最初の操作をサブスクライブして、最初の操作を呼び出すのは「正しい」方法ではないと思います。

これは何か?

this.http.post('http://localhost/auth/token', creds, { 
    headers: headers 
}) 
.map(res => res.json()) 
.do(
    // validate token 
    // decode token 
) 
.thenDo(
    // get user details 
    this.http.get(url, options) 
    .map(res => res.json()) 
    .do(
     //save user and token in localStorage 
    ) 
) 

答えて

0

私はRxjs do and thenDo機能について多くを知らないが、はい、あなたがflatMapを使用し

このような
this.http.post('http://localhost/auth/token', creds, { 
     headers: headers 
    }) 
    .map(res => { 
     return [{status: res.status , json: res.json()}] 
     }) 
    .subscribe(res=>{ 
     if(res[0].status == 200){ // do you action depends on status code you got assuming 200 for OK response 
      this.validateToken() // Validate your token here in some method named as validateToken 
      this.decodeToken() // decode token here in this method 
      this.getUserDetail() //if everything worked fine call your another get request in another method 
     } 
     }, 
     err => { 
      console.log(err, err.status) //catch your error here 
     }) 

     getUserDetail(){ 
      // make http get request for user detail and saveing into locastroage 
     } 
0

を行うことができますが、それぞれが新たな約束や観測を返すことをチェーンオペレーションに適した方法です。 PromiseまたはObservableを返す関数をマップする必要があるたびに、flatMapを使用して解決されたデータを出力するストリームを作成できます。ここでObservableのユーザデータを構築し、最後にそれを購読することができます(localstorageに保存するなど)。

私はあなたの検証コードがPromiseまたはObservableを返す関数であると仮定しています。

const options = { headers }; 
const user$ = this.http.post('http://localhost/auth/token', creds, options) 
    .map(res => res.json()) 
    .flatMap(validationFunctionThatReturnsAPromise) 
    .flatMap(authResponse => { 
    // get user details 
    return this.http.get(url, options).map(res => res.json()); 
    }); 

user$.subscribe(user => /** do something with the user data **/); 
関連する問題