2016-08-18 104 views
1

我正在做一個應用程序與angular2和@ ngrx /店...我新rxjs和思考在一種被動的方式...真正掙扎如何observables是鏈。rxjs與角2 - 如何鏈可觀察流

我有一個權威性的效果......目前看起來像

@Effect() authenticate$ = this.updates$ 
.whenAction(AuthActions.AUTHENTICATE_REQUEST) 
.switchMap(update => this.api.post('/authenticate', update.action.payload) 
    .map((res:any) => this.authActions.authenticateSuccess(res.json())) 
    .catch((err:any) => Observable.of(this.authActions.authenticateError(err))) 
); 

我想要做的是鏈上的兩個額外的動作,當請求成功。

  1. 成功後用this.router.navigate(['/'])導航到「home」頁面。
  2. 存放在localStorage的服務的憑證this.authService.store(credentials)

什麼我需要做的流將這些行動?

+0

您正在調度authenticateSuccess操作,所以您應該在另一個效果中處理此操作。當你有多種認證方式時,這特別有用。 – j2L4e

回答

1

假設最後2條語句的執行順序是無關緊要的,所有你需要做的就是在當前語句的結束追加

.flatMap(() => 
{ 
    this.router.navigate(['/']); 
    this.authService.store(credentials); 
}); 
+0

謝謝...好吧,會給你一個去。是.switchMap之後?或在捕獲後? – markstewie

+0

是的,在.switchMap – hholtij

+0

得到TypeScript錯誤之後...''()=> void'的參數不能分配給類型爲'(value:Action,index:number)=>的參數參數<{}> |承諾<{}> | ArrayLike <{}>'.' – markstewie

0

最好的解決辦法是讓你的effect這樣並添加另一個反應到這樣的成功行動:

@Effect({dispatch: false}) authenticateSuccess$ = this.updates$ 
.whenAction(AuthActions.AUTHENTICATE_SUCCESS) 
.do(credentials => { 
    this.router.navigate(['/']); 
    this.authService.store(credentials); 
}); 

{dispatch: false}的意思是「應對這種行動,但不發送另一個」。