2016-08-19 43 views
1

RxJS的新功能,使用Angular2 & @ ngrx/store & /效果。RxJS- A​​ngular2 - 条件流

我想解决如何使一个流来处理条件结果从一个服务...这是解决,如果用户登录或应用程序第一次运行时检查是否auth凭据存储在LocalStorage中。

这可能是完全错误的方式来处理这个问题,所以任何建议的赞赏。

目前,我有一个效果

@Effect() check$ = this.updates$ 
.whenAction(AuthActions.AUTHENTICATE_CHECK) 
.map(update => this.authService.checkAuth()) 
// now what? 
// returns an observable of false, or a Auth object if LS info found 
// needs to return 
// this.authActions.authenticateCheckResult(res) if ok and 
// this.authActions.authenticateCheckError() if not ok 

而且在authServicecheckAuth方法是这样的......

checkAuth():Observable { 
this._user = <AuthAPI>this.ls.getObject(AuthService.LS_AUTH_KEY); 

if(this._user && this._user.accessToken) { 
    return Observable.of(this._user); 
} 
else { 
    return Observable.of(false); 
} 
} 

更新

我有它正在这样做......

@Effect() check$ = this.updates$ 
.whenAction(AuthActions.AUTHENTICATE_CHECK) 
.map(update => this.authService.checkAuth()) 
.map(result => { 
    if(!result) { 
    return this.authActions.authenticateCheckError(false); 
    } else { 
    return this.authActions.authenticateCheckSuccess(result) 
    } 
}); 

//

checkAuth():AuthAPI { 
this._user = <AuthAPI>this.ls.getObject(AuthService.LS_AUTH_KEY); 

if(this._user && this._user.accessToken) { 
    return this._user; 
} 
else { 
    return null; 
} 

}

这是这样做的一个有效途径,或是否有更好的办法?

+1

看起来好像没什么问题。 –

+0

很酷,谢谢。 – markstewie

回答

0

你也可以连接你的电话一样

checkAuth():Observable<AuthAPI> { 
    return Rx.Observable.of(<AuthAPI>this.ls.getObject(AuthService.LS_AUTH_KEY)) 
         .filter(user => user) 
         .filter(user.accessToken) 
         .defaultIfEmpty(null)