Angular 2 - ID删除方法ID不起作用

时间:2017-10-08 11:36:50

标签: java angular http http-delete

我正在尝试从表中删除一个对象,将其作为参数传递给组件,但是,当我最终调用后端时,对象的ID始终为null。

我的HTML代码如下所示:

<tr *ngFor="let articulo of articulos | nombre: nombreText | familia: familiaText | codigo: codigoText | paginate: {itemsPerPage: 15, currentPage:page, id: '1' };">
  <td>{{articulo.codigo}}</td>
  <td>{{articulo.proveedor}}</td>
  <td>{{articulo.nombre}}</td>
  <td>{{articulo.familia}}</td>
  <td>{{articulo.precio}}</td>
  <td>{{articulo.fechaModificacion}}</td>
  <td>{{articulo.anotaciones}}</td>
  <td>
      <div class="btn-group btn-group-sm pull-right" >
        <button class="btn btn-xs pink whiteFont" title="Editar artículo">
          <i class="fa fa-pencil" aria-hidden="true"></i>
        </button>
        <button (click)="deleteArticulo(articulo); $event.stopPropagation()" class="btn btn-xs pink whiteFont" title="Eliminar artículo">
          <i class="fa fa-trash-o" aria-hidden="true"></i>
        </button>
      </div>
  </td>
</tr>

ArticulosComponent.ts删除方法:

deleteArticulo(articulo:Articulo):void {        this.articulosService.delete(articulo.id).subscribe();    }

ArticulosService.ts删除方法:

delete(id: number) {
    const url = `${this.articulosURL}/${id}`;
    return this.http.delete(url, { headers: this.headers }).map(() => null);
}

最后,我的java控制器:

@DeleteMapping("/articulos/{id}")
public ResponseEntity<Void> deleteArticulo(Integer id){
     try {
         articulosService.delete(id);
         return new ResponseEntity<Void>(HttpStatus.OK);
     } catch(Exception e) {
         return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
     }
}

1 个答案:

答案 0 :(得分:0)

原因是您的Java后端不知道如何映射传递给它的值。在这种情况下,@PathVariable

@DeleteMapping("/articulos/{id}")
public ResponseEntity<Void> deleteArticulo(@PathVariable Integer id){
    try {
        articulosService.delete(id);
        return new ResponseEntity<Void>(HttpStatus.OK);
    } catch(Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

这不是实践,因为PathVariable是一个字符串,Java可能经常在转换为Integer时抛出错误。以下是我将如何做到这一点。

publuc class Args {
  id: string;
  val: string;
}


delete(id: number) {
   let optionsArray: Args[] = [
      {id: "id" val: id.toString()}
    ];
   return this.http.delete(this.articulosURL, this.addRequestOptions(oprionsArray, null)).map(() => null);
}

/***
 * Generates default headers I.E. #Authorization and append any optional headers provided
 * @param {Args[]} args an array of Args[KEY, Value]
 * @returns {Headers}
 */
private addHeader(args: Args[]): Headers {
  let headers: Headers = new Headers();

  // Use this block only if you have Spring OAuth2 security or any other security that require Authorization client id 
    let a: Args = new Args;
    a.id = "Authorization";
    a.val = "your client id";
    headers.append(a.id, a.val);
  // END

  if (args == null) return headers;
  args.forEach(a => {
    headers.append(a.id, a.val);
  });
  return headers;
}

/***
 * Generates default headers as default option and add any provided search parameters to the #RequestOptions
 * @param {Args[]} args an array of request parameters
 * @param {Args[]} headers an array of optional headers
 * @returns {RequestOptions}
 */
private addRequestOptions(args: Args[], headers: Args[]): RequestOptions {
  let options: RequestOptions = new RequestOptions();
  options.headers = this.addHeader(headers);
  options.params = new URLSearchParams();
  if (args == null || args == []) return options;
  args.forEach(a => {
    options.params.append(a.id, a.val);
  });
  return options;
}
@DeleteMapping("/articulos/", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity deleteArticulo(@RequestParam String id){
    try {
        articulosService.delete(Integer.valueOf(id));
        return new ResponseEntity<Void>(HttpStatus.OK);
    } catch(Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}