代码之家  ›  专栏  ›  技术社区  ›  Martin Andersen

以角度向用户显示服务器端消息

  •  0
  • Martin Andersen  · 技术社区  · 6 年前

    这是后置动作

    [HttpPost("[action]")]
    public IActionResult Create([FromBody]Hit hit)
    {
        try
        {
            if (hit == null)
                return BadRequest("Hit object is null");
    
            if (!ModelState.IsValid)
                return BadRequest("Invalid model object");
    
            var newHit = _hitRepository.Add(hit);
            return Ok(newHit);
        }
        catch (Exception ex)
        {
            return ex.InnerException.Message.Contains("duplicate key") 
                ? BadRequest($"Et Hit med søgeretningen {hit?.SearchDirection} og ordet {hit?.SearchWord} findes allerede") 
                : StatusCode(500, "Internal server error");
        }
    }
    

    在Angular我有一个使用post方法的服务

    create(hit: Hit): Observable<Hit> {
        return this.httpClient.post<Hit>(
          `${environment.apiUrl}/${this.hitRoute}/create`,
          hit
        );
    }
    

    我一直在玩管道和catchError函数,但没有运气

    create(hit: Hit): Observable<Hit> {
        return this.httpClient.post<Hit>(
          `${environment.apiUrl}/${this.hitRoute}/create`, hit)
        .pipe(
          catchError((error: HttpErrorResponse) => {
            return new ErrorObservable(
              `Fejl ved oprettelse af nyt Hit. ${error.message || 'Unknown'} `
            );
          })
        );
    }
    

    Angular组件有一个使用服务的create函数

    addWordToHits() {
        const hit = {
          searchDirection: this.selectedBook,
          searchWord: this.selectedItem.word
        } as Hit;
    
        this.hitService.create(hit).subscribe(
          (data: Hit) => {
            this.messageService.add({
              severity: 'success',
              summary: 'Hit oprettet',
              detail: data.searchWord
            });
          },
          (err: HttpErrorResponse) => {
            this.messageService.add({
              severity: 'error',
              summary: 'Hit kunne ikke oprettet',
              detail: err.message
            });
          }
        );
    }
    

    详细信息错误消息不是来自HttpClient而是来自RxJs:

    "Observable_1.Observable.throw is not a function"
    

    有很多关于如何使用Angular构建完整的CRUD应用程序的教程

    这是一个很普通的问题,怎么会是一个很普通的服务世界?

    enter image description here

    2 回复  |  直到 4 年前
        1
  •  0
  •   Vivek Kumar    6 年前
    import { throwError } from 'rxjs';
    
    create(hit: Hit): Observable<Hit> {
        return this.httpClient.post<Hit>(
          `${environment.apiUrl}/${this.hitRoute}/create`, hit)
        .pipe(
          catchError((error: HttpErrorResponse) => {
            return throwError(
              `Fejl ved oprettelse af nyt Hit. ${error.message || 'Unknown'} `
            );
          })
        );
    }
    

    创建了简单的代码来复制

    import { throwError } from 'rxjs';
    import { catchError } from 'rxjs/operators';
    import { HttpClient } from '@angular/common/http';
    
    @Component({})
    export class SomeComponent {
    
      constructor(private httpClient: HttpClient) {
        this.testCatchError();
      }
    
      testCatchError() {
        this.httpClient
          .get('http://localhost:3000/api/postss')
          .pipe(
            catchError(error => {
              console.log('inside of catchError');
              return throwError({ msg: 'Hello' });
            })
          )
          .subscribe(
            data => {
              console.log(`testRetryOperator >>> data >>> `, data);
            },
            error => {
              console.warn('testRetryOperator >>> error >> ', error);
            }
          );
      }
    

    enter image description here

        2
  •  0
  •   Sunil Singh    6 年前

    处理错误的最佳方法之一是使用 Interceptor . 最好的是,您可以在所有API的顶层处理错误。所以需要编写相同的重复代码来处理http错误。

    http协议-错误.interceptor.ts

    import { HttpEvent, 
             HttpInterceptor, 
             HttpHandler, 
             HttpRequest, 
             HttpResponse,
             HttpErrorResponse} from '@angular/common/http';
    import { Observable, throwError } from 'rxjs';
    import { catchError } from 'rxjs/operators';
    
    export class HttpErrorInterceptor implements HttpInterceptor {
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
        return next.handle(request)
           .pipe(
             catchError( (error: HttpErrorResponse) => { 
                let errMsg = '';
                // Client Side Error
                if (error.error instanceof ErrorEvent) {        
                  errMsg = `Error: ${error.error.message}`;
                } 
                else {  // Server Side Error
                  errMsg = `Error Code: ${error.status},  Message: ${error.message}`;
                }
                return throwError(errMsg);
              })
           )
      }
    }  
    

    应用程序模块.ts

    @NgModule({
      imports: [...], 
      declarations: [...],
      bootstrap:    [....],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: HttpErrorInterceptor, //<-- provide the interceptor
          multi: true,
        },
        CustomerService,...]
    })