获取状态代码不起作用httpClient angular

时间:2018-04-12 13:11:26

标签: angular

首先,我会说我对角度全新,阅读文档说得到回应我们应该使用{observe:response}所以在我的服务中我做了这个

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

  }

updateTrucks(truck: Truck): Observable<Truck> {
    return this.http.put(this.baseUrl, JSON.stringify(truck), {observe: 'response'})
      .pipe(
      //  map(this.extractData),
       // tap(data => console.log(JSON.stringify(data))),
        catchError(this.handleError));
  }

我希望我的html通过检查状态代码返回消息成功或冲突,所以我使用的是statuscode:number作为组件中的var和* html中的* ngIf来检查状态代码值,这是我的组件和一点点html谢谢你的帮助

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('descriptions').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)
          }

        });

    }
  }

我的html看起来像这样

 <br/>
              <div *ngIf="statusCode; else processing">
                <div *ngIf="statusCode === 400" [ngClass] = "'success'">
                  Truck already exists.
                </div>

                <div *ngIf="statusCode === 201" [ngClass] = "'success'">
                  Truck added successfully.
                </div>
                <div *ngIf="statusCode === 409" [ngClass] = "'success'">
                  Truck already exists.
                </div>

在控制台中,当我成功发布时,我没有得到任何回复,当我试图让冲突得到时我得到了

webpack-internal:///./src/app/services/trucks/truck.service.ts:56 Http failure response for http://localhost:8088/trucks: 409 Conflict

这是我的错误处理程序和响应

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

  private handleError (error: HttpErrorResponse) {
    console.error(error.message || error);
    return Observable.throw(error.status);
  }

0 个答案:

没有答案