2016-08-21 18 views
3

を結合する方法をngrx /店舗/効果@アンギュラ...私はupdate.action.payload内でこのRxJS/2 /私は@ ngrx /ストア&効果でAngular2を使用していたアクション

@Effect() authenticate$ = this.updates$ 
    .whenAction(AuthActions.AUTHENTICATE_REQUEST) 
    .switchMap(update => this.api.post('/authenticate', update.action.payload) 
    // somehow use data in the original `update` to work out if we need to 
    // store the users credentials after successful api auth call 
    .map((res:any) => this.authActions.authenticateSuccess(res.json())) 
    .catch((err:any) => Observable.of(this.authActions.authenticateError(err))) 
) 

のような認証の効果を持っていますオブジェクトはrememberMeフラグです。だから... trueに設定すると、LocalStorageサービスの後に資格情報を保存する必要があります。のapiリクエストは正常に返されましたが、エラーがある場合は明らかになりません。

これは、switchMapオペレータの内部ではどのように達成できますか?私たちはapiのポストコールの結果にのみアクセスできますか?


WORKING CODE

@Effect() authenticate$ = this.updates$ 
.whenAction(AuthActions.AUTHENTICATE_REQUEST) 
.switchMap(update => this.api.post('/authenticate', update.action.payload) 
    .map((res:any) => { 
    return { 
     res: res, 
     update: update 
    }; 
    }) 
    .do((result:any) => { 
    if(result.update.action.payload.remember) { 
     this.authService.setAuth(result.res.json()); 
    } 
    }) 
    .map((result:any) => this.authActions.authenticateSuccess(result.res.json())) 
    .catch((err:any) => Observable.of(this.authActions.authenticateError(err))) 
); 
+0

私が行うには一つまたは二つの方法を考えることができますしかし、彼らはハッキーになるだろう。最もクリーンな方法(IMHO)は、 'rememberMe'フィールドをAPIレスポンスに戻すことになるでしょう - これは可能でしょうか? – drewmoore

+0

これは間違いなく最もクリーンなはずですが、残念ながら私はバックエンドが返すものを制御することはできません。 – markstewie

答えて

3

BELOW ANSWER FROMあなたはupdateを含むように、観察postmapすることができるはずです。

@Effect() authenticate$ = this.updates$ 
    .whenAction(AuthActions.AUTHENTICATE_REQUEST) 
    .switchMap(update => this.api.post('/authenticate', update.action.payload).map((res:any) => { 
    return { 
     res: res, 
     update: update 
    }; 
    })) 
    .do((result:any) => { ... whatever it is you need to do with result.update ... }) 
    .map((result:any) => this.authActions.authenticateSuccess(result.res.json())) 
    .catch((err:any) => Observable.of(this.authActions.authenticateError(err))) 
) 
+0

Thanks @cartant!これは私がやろうとしていたことです! (.switchMapの最後から余分な括弧を削除するだけです) – markstewie

+0

これはうまくいかず、 'switchMap()'の引数はObservableを返す必要があります。 – drewmoore

+0

これはうまくいきます...上記のコードを編集して作業コードを表示します... – markstewie

関連する問題