简体   繁体   English

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

[英]How do i catch status code with httpClient angular

I am working with http client i have a in my service 我正在使用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);
  }

and a create method post 和一个创建方法的帖子

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));
  }

In my component im trying to get the status code ,the method succesfully posts but i have errors when i try a duplicate truckCode which i want to be returned as a message in the app. 在我的组件我试图获取状态代码,该方法成功发布但我有错误当我尝试重复的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);

    }
  }

so in my html i did this to get the status code but it doesnt work, ii think there is a problem with the service as it maps the body and not a status code what can i do ? 所以在我的HTML中,我这样做是为了获取状态代码,但它不起作用,ii认为服务存在问题,因为它映射了正文而不是状态代码我该怎么办? here is my html part of it 这是我的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>

the #processing part works but status code doesnt any help please thank you. #processing部分有效,但状态代码没有任何帮助,请谢谢。

How it looks now , after i added it gave error status does not exist on type truck, what could it b 它现在看起来如何,在我添加它后给出错误状态在卡车类型上不存在,它可能是什么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});

You have to cast the error first to Response-object. 您必须首先将错误转发给Response-object。 Then you can access the error code. 然后,您可以访问错误代码。

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 });

}

This should do. 这应该做。

I did that by simply: 我这样做只是:

In your truckService: 在您的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));
      }

In your component: 在您的组件中:

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)
        }

    });

  }
}

Edit: Better approach that works. 编辑:更好的方法有效。 Get that in your subscribe and assign it to the variable you want. subscribe获取并将其分配给您想要的变量。 Leaving error just for logging, that way you can use data you retrieve. 仅为记录留下错误,这样您就可以使用检索的数据。 error is used for errorHandling, not passing data. error用于errorHandling,不传递数据。 That you will do on .subscribe . 你将在.subscribe.subscribe

You can see that this way you are receiving a full Response with everything you need, like headers, ok, status, statusText, type, url and _body. 你可以通过这种方式看到你正在接收一个完整的响应,包括你需要的一切,比如header,ok,status,statusText,type,url和_body。

Hope it helps 希望能帮助到你

So everything was ok except that this is angular 4 and in the static method throw doesnt come with the import of rxjs/Observable, this was the problem 所以一切都很好,除了这是角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 
  }

you to explicitly do import 你明确地做导入

 import 'rxjs/add/observable/throw'; 

with this it will now work 有了它,它现在可以工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM