angular - 在一个 Observable 中设置逻辑?角
问题描述
当我发送无效的表单时,它会发送给我 2 次 http post 请求。
<form [formGroup]="formG" (submit)="onSubmitForm()">
<input type="text formControlName="userName">
<button type="submit">
</form>
ts里面
onSubmitForm() {
this.service.addUserName(this.formG.value).subscribe((res:any) => {
console.log('succes response');
})
}
内部服务:
public addUserName(userName) {
return this.httpClient.httpPostGlobal<any[]>(`addNewUser/${userName}`, null);
}
httpPost有点复杂。作为全球服务制造。
httpPostGlobal 的全球服务内部是->
public httpPostGlobal<T>(path: string, data: any): Observable<HttpResponse<T>> {
let postMetodData = (observer: Observer<HttpResponse<T>>) => {
this.getTokenFromServiceData().subscribe(
userToken => {
let httpOptions = {
observe: 'response' as 'response',
headers: new HttpHeaders({
Authorization: ,
accept: 'application/json'
}),
};
this.http.post<T>(environment.url + path, data, httpOptions)
.pipe(
catchError((err: HttpErrorResponse) => {
return throwError(err);
}))
.subscribe(
response => this.successCallback(response, observer),
(error: HttpErrorResponse) => this.errorCallback(error, observer)
);
}
);
};
let obs = new Observable<HttpResponse<T>>(postMetodData);
return obs;
}
这个函数里面有问题......可能是catchError,但我不知道。
唯一的问题是它重复了 2 次 http 请求。其他一切都有效。添加时并且响应为 200 或 201 并且其他一切正常。唯一的问题是当提交无效的表单并且后端返回 422 时,它会触发相同的请求 2 次,并且如果我在表单上只按一次提交。
successCallback 只是:
private successCallback<T>(response: HttpResponse<T>, observer: Observer<HttpResponse<T>>): void {
if ((response.status === 200 || response.status === 204 || response.status === 201) &&
(response.statusText === HttpService.OK || response.statusText === HttpService.NO_CONTENT
|| response.statusText === HttpService.CREATED)) {
observer.next(response);
} else {
observer.error(response);
}
observer.complete();
}
解决方案
无论第一个活动是否有效,您都在这里订阅了多个活动。相反,您应该将此逻辑放入一个 Observable 中。
我还修复了一些问题,并使用了一些打字稿来清理。
public httpPostGlobal<T>(path: string, data: any): Observable<HttpResponse<T>> {
return this.getTokenFromServiceData().pipe(
switchMap(userToken => {
const httpOptions = {
observe: 'response' as 'response', // this probably isnt needed as this is already the default value
headers: new HttpHeaders({
Authorization: `${userToken}`,
accept: 'application/json', // this probably isnt needed as this is already the default value
}),
};
return this.http.post<T>(`${environment.url}${path}`, data, httpOptions);
}),
map(response => this.successCallback(response, observer)),
catchError((err: HttpErrorResponse) => this.errorCallback(error, observer)),
);
}
推荐阅读
- swift - 订阅发布者时无法获取最新值
- ios - SwiftUI / iOS / iPhone如何在存储之前加密数据/图像以及在哪里/如何在本地存储,一般最佳实践?
- sql - 在 SQL Server 中生成字母数字序列
- sql - Postgesql函数子查询、求和、计数、排序
- python - Visual Studio 不显示 Python 文件的方法和其他项目列表
- loops - 如何在 RPGLE 中按 KEY FIELD DATE 进行 LOOP 记录?
- python - 使用 matplotlib 制作 3d 冲浪动画
- handlebars.js - 有没有办法根据用户的国家/地区输出数组的特定部分?
- php - 检查数组值是否包含浏览器国家代码
- css - 如何使用 NodeJS 应用程序修复资产上的 NGiNX 404