gpt4 book ai didi

Angular2 + ngrx/store 用于处理失败的 HTTP 请求

转载 作者:太空狗 更新时间:2023-10-29 17:12:01 25 4
gpt4 key购买 nike

我想要一个简单的代码路径来创建和调度 HTTP 操作。我想做的是:

this.http.request(...)
.map((res: Response) => res.json())
.catch((err: any) => err.json())
.map((payload: any) => { type: 'SUCCESS', payload })
.catch((payload: any) => { type: 'FAILURE', payload})
.subscribe((action: Action) => this.store.dispatch(action));

这样,成功和失败响应都被转换为 JSON,然后根据成功/失败标准分配正确的缩减类型,以便商店可以正常运行。 (考虑返回 200 或 401 的用户登录成功和失败)。

是否有更清洁或更好的处理方式?当前第二个 .catch 不能正常播放,因为它没有返回可观察值。

欢迎提出建议或其他解决方案?

最佳答案

来自example-app来自 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 上设置 Effects:

@NgModule({
imports: [
StoreModule.provideStore(reducer),
EffectsModule.run(AuthEffects),
RouterStoreModule.connectRouter(), // optional but recommended :D
],
declarations: [...],
providers: [AuthService, LocalStorageService, ...]
})
export class AuthModule {}

在存储库的文档文件夹中阅读有关 ngrx/effects 的更多信息。

关于Angular2 + ngrx/store 用于处理失败的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35384085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com