从示例应用程序中ngrx
,对于这种情况,建议使用@Effects(检查文档文件夹),而IMO是一种更清晰的方法,请检查服务:
@Injectable()
export class AuthService {
private headers: Headers;
private API_ENDPOINT: string = "/api/user/";
public constructor(
private http: Http,
private localStorageService: LocalStorageService
) {
this.headers = new Headers({ 'Accept': 'application/json' });
}
public login(email: string, password: string): Observable<AuthUser> {
return this.http
.post(this.API_ENDPOINT + 'login', { 'email': email, 'password': password }, this.headers)
.map(res => res.json().data as AuthUser)
.catch(this.handleError);
}
private handleError(error: Response | any) {
let body = error.json();
// .. may be other body transformations here
console.error(body);
return Observable.throw(body);
}
}
并检查效果:
@Injectable()
export class AuthEffects {
constructor(
private actions$: Actions,
private authService: AuthService,
private localStorageService: LocalStorageService
) { }
@Effect() logIn$: Observable<Action> = this.actions$
.ofType(auth.ActionTypes.LOGIN)
.map((action: Action) => action.payload as LoginCredentials)
.switchMap((credentials: LoginCredentials) => this.authService.login(credentials.email, credentials.password))
.do((user: AuthUser) => this.localStorageService.setUser(user))
.map((user: AuthUser) => new auth.LoginSuccessAction(user))
.catch((error) => of(new auth.FlashErrors(error)));
}
当然,您需要在 appModule 上设置效果:
@NgModule({
imports: [
StoreModule.provideStore(reducer),
EffectsModule.run(AuthEffects),
RouterStoreModule.connectRouter(), // optional but recommended :D
],
declarations: [...],
providers: [AuthService, LocalStorageService, ...]
})
export class AuthModule {}
从 repo 的 docs 文件夹中阅读更多关于 ngrx/effects 的信息。