typescript RXJS Angular -使用.subscribe和Observable进行错误处理

dm7nw8vv  于 2023-08-07  发布在  TypeScript
关注(0)|答案(3)|浏览(173)

我有一个后端API来创建新产品。前端angular代码需要调用后端API。如何使用**.subscribe**进行错误处理。我正在使用 HTTPClientObservable,并且一直在阅读RXJS如何利用错误处理,
应用程序应该将其称为Observable和.subscribe()。
api /create应该处理成功和失败(错误)-如果API返回200:它应该打印成功-如果API返回400,应该抛出错误

伪代码

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

ID = 'foo';
            this.http.post('/api/create', {
                productName: this.form.value.productName,
                productValue: this.form.value.productValue,
            }).subscribe(
                resp => this.onSubmitSuccess(resp), err => this.onSubmitFailure(err)
            );

private onSubmitSuccess(resp) {
        console.log(resp);
        this.ID = resp.ID;
        this.submitSuccess = true;
        this.submitFailed = false;
    }

    private onSubmitFailure(resp) {
        console.log(resp);
        this.submitFailed = true;
        this.submitSuccess = false;
    }  ```

字符串

bwitn5fc

bwitn5fc1#

早期的版本是这样的:

this.http.get(url).subscribe(
 data =>
 {
   //do something
 },
 error =>
 {
   //handle error
 }
);

字符串
在最新版本中,他们已弃用此格式。现在你必须做:

this.http.get(url).subscribe(
 {
   next: (data) => 
   {
     //do something
   },
   error: (error) =>
   {
     //handle error
   }
 }
);

p3rjfoxz

p3rjfoxz2#

处理请求错误。Angular官方文档

getConfig() {
  return this.http.get<Config>(this.configUrl)
    .pipe(
      catchError(this.handleError)
    );
}

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error.message);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${error.error}`);
  }
  // return an observable with a user-facing error message
  return throwError(
    'Something bad happened; please try again later.');
};

字符串

lrpiutwd

lrpiutwd3#

如果您不能使用async管道而必须使用subscribe,则使用pipe操作符是最佳实践,并允许您在组件被销毁时取消订阅。使用操作符来放置逻辑更实用,因为subscribe应该仅用于显示正在观察流。它可能是这样的:

ID = 'foo';
  onDestroy = new Subject<boolean>();

  this.http.post('/api/create', {
      productName: this.form.value.productName,
      productValue: this.form.value.productValue,
  }).pipe(
    catchError(err => {
      onSubmitFailure(err);
      return of(err);
    }),
    takeUntil(this.onDestroy),
    tap(resp => onSubitSuccess(resp)),
  ).subscribe();

  onSubmitSuccess(resp) {
      console.log(resp);
      this.ID = resp.ID;
      this.submitSuccess = true;
      this.submitFailed = false;
  }

  onSubmitFailure(resp) {
      console.log(resp);
      this.submitFailed = true;
      this.submitSuccess = false;
  } 

  ngOnDestroy() {
      this.onDestroy$.next(true);
      this.onDestroy$.unsubscribe();
  }

字符串

相关问题