如何使用httpClient angular捕获状态代码

时间:2018-04-11 21:36:00

标签: javascript angular

我正在使用http客户端我的服务

  private extractData(response: HttpResponse<Truck>) {
    const body = response;
    return body || {};
  } 

  private handleError(err: HttpErrorResponse) {
    let errorMessage: string;

    // A client-side or network error occurred.
    if (err.error instanceof Error) {
      errorMessage = `An error occurred: ${err.error.message}`;
    }
  ,
    else {
      errorMessage = `server side  ${err.status}, body was: ${err.error}`;
    }

    console.error(errorMessage || err);
    return Observable.throw(err.status);
  }

和创建方法帖子

createTruck(truck: Truck): Observable<number> {
     return this.http.post(this.baseUrl, JSON.stringify(truck), {headers: this.headers})
      .pipe(
        map(this.extractData),
        tap(data => console.log(JSON.stringify(data))),
        catchError(this.handleError));
  }

在我试图获取状态代码的组件中,该方法成功发布但我在尝试重复的truckCode时出错,我希望将其作为应用程序中的消息返回。

processForm() {

    this.processValidation = true;
    if (this.truckForm.invalid) {
      return; //Validation failed, exit from method.
    }

    // if we are here then all good
     this.preProcessConfigurations()

    let truckCode = this.truckForm.get('truckCode').value.trim();
    let date = this.truckForm.get('date').value.trim();
    let description = this.truckForm.get('description').value.trim();


    if (this.truck.truckId == undefined) {
      let truck= new Truck(null, truckCode, date, description);

      this.truckService.createTruck(truck).subscribe((truck) => {
        console.log(truck);
        this.router.navigate(['/trucks'])
      },
        errorCode => this.statusCode = errorCode);

    }else {
      let truck= new Truck(this.truck.truckId, truckCode, date, description);

      this.truckService.updateTrucks(truck).subscribe((truck) => {
        console.log(truck);
        this.router.navigate(['/trucks'])
      }, errorCode => this.statusCode = errorCode);

    }
  }

所以在我的html中,我这样做是为了获取状态代码,但它不起作用,我认为服务有问题,因为它映射身体而不是状态代码我该怎么办?这是我的html部分

           <!--form end-->
            </form>
            <br/>
            <div *ngIf="statusCode; else processing">

              <div *ngIf="statusCode === 201" [ngClass] = "'success'">
                Article added successfully.
              </div>
              <div *ngIf="statusCode === 409" [ngClass] = "'success'">
                Article already exists.
              </div>
              <div *ngIf="statusCode === 400" [ngClass] = "'success'">
                Article already exists.
              </div>
              <div *ngIf="statusCode === 200" [ngClass] = "'success'">
                Article updated successfully.
              </div>
              <div *ngIf="statusCode === 204" [ngClass] = "'success'">
                Article deleted successfully.
              </div>
              <div *ngIf="statusCode === 500" [ngClass] = "'error'">
                Internal Server Error.
              </div>
            </div>

            <ng-template #processing>
              <img *ngIf="requestProcessing" src="assets/images/loading.gif">
            </ng-template>
          </div>

#processing部分有效,但状态代码没有任何帮助,请谢谢。

它现在看起来如何,在我添加后它给出错误状态在卡车上不存在,它可能是什么b

e

  this.truckService.createTruck(truck).subscribe((truck) => {
    console.log(truck['_body']);
    this.router.navigate(['/trucks'])
  }, this.statusCode = truck.status;
    // (errorCode: Response) => { this.statusCode = errorCode.status})
    // errorCode => this.statusCode = errorCode); 
  this.truckService.updateTrucks(truck).subscribe((truck) => {
    console.log(truck['_body']);
    this.router.navigate(['/trucks'])
  },this.statusCode = truck.status;
    // (errorCode: Response) => { this.statusCode = errorCode.status});

3 个答案:

答案 0 :(得分:1)

您必须先将错误转发给Response-object。 然后,您可以访问错误代码。

import { Response } from '@angular/http';

if (this.truck.truckId == undefined) {
  let truck= new Truck(null, truckCode, date, description);

  this.truckService.createTruck(truck).subscribe((truck) => {
    console.log(truck);
    this.router.navigate(['/trucks'])
  },
    (errorCode: Response) => { this.statusCode = errorCode.status });

}else {
  let truck= new Truck(this.truck.truckId, truckCode, date, description);

  this.truckService.updateTrucks(truck).subscribe((truck) => {
    console.log(truck);
    this.router.navigate(['/trucks'])
  }, 
     (errorCode: Response) => { this.statusCode = errorCode.status });

}

应该这样做。

答案 1 :(得分:1)

我这样做只是:

在您的truckService:

import { map, tap, catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

...

        createTruck(truck: Truck): Observable<number> {
         return this.http.post(this.baseUrl, JSON.stringify(truck), {headers: this.headers})
          .pipe(
            map(this.extractData),
            tap(data => console.log(JSON.stringify(data))),
            catchError(this.handleError));
      }

在您的组件中:

processForm() {

  this.processValidation = true;
  if (this.truckForm.invalid) {
    return; //Validation failed, exit from method.
  }

  // if we are here then all good
   this.preProcessConfigurations()

  let truckCode = this.truckForm.get('truckCode').value.trim();
  let date = this.truckForm.get('date').value.trim();
  let description = this.truckForm.get('description').value.trim();


  if (this.truck.truckId == undefined) {
    let truck= new Truck(null, truckCode, date, description);

    this.truckService.createTruck(truck).subscribe((truck) => {

      this.router.navigate(['/trucks']);
    },
    error => {
      if(error){
        this.statusCode=error;
        console.log('error code'+ this.statusCode)
      }
    });

  }else {
    let truck= new Truck(this.truck.truckId, truckCode, date, description);

    this.truckService.updateTrucks(truck).subscribe((truck) => {

      this.router.navigate(['/trucks']);
    },
    error => {

        if(error){
          this.statusCode=error;
          console.log('error code'+ this.statusCode)
        }

    });

  }
}
  

编辑:更好的方法有效。在subscribeerror中获取   将它分配给您想要的变量。仅为记录而留下错误,   这样你就可以使用你检索的数据。 .subscribe用于   errorHandling,不传递数据。您将在{{1}}上完成。

您可以通过这种方式看到您收到所需内容的完整回复,例如标题,确定,状态,statusText,类型,网址和_body。

希望有所帮助

答案 2 :(得分:1)

所以一切都很好,除了这是角4并且在静态方法中抛出并没有导入rxjs / Observable,这就是问题

private handleError(error: HttpErrorResponse| any) {
    let errorMessage: string;

    // A client-side or network error occurred.
    if (error.error instanceof Error) {
      errorMessage = `An error occurred: ${error.error.message}`;

    } else {
      errorMessage = `server side  ${error.status}, body was: ${error.error}`;
    }

    console.error(error.ok || error);
    return Observable.throw(error.status);// observable throw is not a function 
  }

你明确地做导入

 import 'rxjs/add/observable/throw'; 

使用它现在可以正常工作