首页 > 解决方案 > 在一个 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();
}

标签: angular

解决方案


无论第一个活动是否有效,您都在这里订阅了多个活动。相反,您应该将此逻辑放入一个 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)),
  );
}

推荐阅读