Angular 2 - 通过 ID 的 HTTP 删除方法不起作用

Angular 2 - HTTP Delete method by ID not working

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

我的 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删除方法:

删除文章(文章:文章):无效{ this.articulosService.delete(articulo.id).订阅(); }

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

原因是您的 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);
    }
}