角度删除实体错误405 HttpRequestMethodNotSupportedException

时间:2018-03-23 01:19:36

标签: html spring angular typescript request

我编写了一个应用程序,它对实体列表进行CRUD操作。 但是例如对于删除实体的情况,结果对话框不会出现。

首先,我有一个HttpService,它是CRUD操作的基础:

@Injectable()
export class HttpService {

    static API_END_POINT = 'http://localhost:8080/api/v0';

    private params: URLSearchParams;

    private headers: Headers;

    private responseType: ResponseContentType;

    constructor(private http: Http) {
        this.params = new URLSearchParams();
        this.headers = new Headers();
    }

delete(endpoint: string): Observable<any> {
        return this.http.delete(HttpService.API_END_POINT + endpoint, this.createOptions()).map(
            response => this.extractData(response)).catch(
                error => {
                    return this.handleError(error);
                });
    }

}

对于实体,我使用Injectable服务(CustomerService):

@Injectable()
export class CustomerService {
    static END_POINT = '/customers';

    constructor(private httpService: HttpService, public snackBar: MatSnackBar) {
    }

   deleteObservable(customer: Customer): Observable<boolean> {
        return this.httpService.delete(CustomerService.END_POINT).map(
            data => {
                this.successful();
                return data;
            }
        );
    }
}

然后是菜单组件,对于每个实体(客户),我可以选择删除它:

菜单组件:

@Component({
    templateUrl: './customers.component.html',
})
export class CustomersComponent implements OnInit {
    static URL = 'customers';

    displayedColumns = [ 'id', 'name', 'address', 'date', 'actions'];
    dataSource: MatTableDataSource<Customer>;
    customers = this.dataSource;

    constructor(public dialog: MatDialog, private customerService: CustomerService) {
    }

...

delete(customer: Customer) {
        this.customerService.readObservable(customer.id).subscribe(
              data => {
                const dialogRef = this.dialog.open(CustomerDeleteDialogComponent);
                dialogRef.componentInstance.customer = data;
                dialogRef.afterClosed().subscribe(
                    result => this.synchronize()
                );
           }
        );
    }
}

菜单html模板:

<mat-card>
    <mat-table #table [dataSource]="dataSource">
        <ng-container matColumnDef="id">
            <mat-header-cell *matHeaderCellDef> Id </mat-header-cell>
            <mat-cell *matCellDef="let item"> {{item.id}} </mat-cell>
        </ng-container>
        <ng-container matColumnDef="name">
            <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
            <mat-cell *matCellDef="let item"> {{item.name}} </mat-cell>
        </ng-container>
        <button mat-icon-button color="accent" (click)="delete(customer)">
            <mat-icon aria-label="Delete">delete</mat-icon>
        </button>
</mat-card>

对话框组件:

@Component({
    selector: 'app-customer-delete-dialog',
    templateUrl: 'customer-delete-dialog.component.html',
    styles: [`.mat-dialog-content {
        display: flex;
        flex-direction: column;
    }`]
})
export class CustomerDeleteDialogComponent implements OnInit {
    customer: Customer;

    constructor(private customerService: CustomerService,
        public dialogRef: MatDialogRef<CustomerDeleteDialogComponent>) { }

    delete(): void {
        this.customerService.deleteObservable(this.customer).subscribe(
            data => this.dialogRef.close()
        );
    }
    ngOnInit(): void {
        if (!this.customer) {}
        this.customer = { id: undefined, name: '', address: '', date: undefined };
        }
}

对话框html模板:

<mat-dialog-content>
    <mat-icon color="warn">warning</mat-icon> <h3>Confirm: Delete Customer. Are you sure?</h3>
</mat-dialog-content>
<mat-dialog-actions>
    <button mat-raised-button mat-dialog-close cdkFocusInitial color="primary">Cancel</button>
    <button mat-raised-button [mat-dialog-close]="true"  (click)="delete()">Ok. Delete</button>
</mat-dialog-actions>

如果我选择删除客户并通过上一个对话框确认,我收到一个例外:

“org.springframework.web.HttpRequestMethodNotSupportedException,message:不支持请求方法'DELETE',路径:/ api / v0 / customers”

Spring或Angular ,我的问题是错误在哪里?因为资源测试角度在哪里正确,我可以使用相同的API来创建客户。任何帮助都会很棒!

如果有帮助,这里是Spring代码:

资源......

@RestController
@RequestMapping(CustomerResource.CUSTOMERS)
public class CustomerResource {

    public static final String CUSTOMERS = "/customers";

    public static final String ID = "/{id}";

    private CustomerController customerController;

    @Autowired
    public void setCustomerController(CustomerController customerController) {
        this.customerController = customerController;
    }

@RequestMapping(value = ID, method = RequestMethod.DELETE)
    public void deleteCustomer(@PathVariable String id) {
        customerController.deleteCustomer(id);
    }

}

...和控制器

@Controller
public class CustomerController {

    @Autowired
    private CustomerDao customerDao;

public void deleteCustomer(String id) {
        if (customerDao.exists(id)) {
            customerDao.delete(id);
        }
    }

}

修改

这是删除请求测试,该测试正确无误:

@Test
    public void deleteCustomer() {
        this.deleteCustomer("222");
    }

    private void deleteCustomer(String id) {
        new RestBuilder<Object>(port).path(contextPath).path(CustomerResource.CUSTOMERS).path(CustomerResource.ID).delete().build();
    }

 @Test
    public void deleteCustomer() {
        this.deleteCustomer("222");
    }

    private void deleteCustomer(String id) {
        new RestBuilder<Object>(port).path(contextPath).path(CustomerResource.CUSTOMERS).path(CustomerResource.ID).delete().build();
    }

此外,POST方法(创建新客户)有效,我认为它类似:

@RestController
@RequestMapping(CustomerResource.CUSTOMERS)
public class CustomerResource {

    public static final String CUSTOMERS = "/customers";

    public static final String ID = "/{id}";

    private CustomerController customerController;

...

@RequestMapping(method = RequestMethod.POST)
    public String createCustomer(@RequestBody CustomerDto customerDto) {
        return customerController.createCustomer(customerDto);
    }

}

1 个答案:

答案 0 :(得分:0)

根据例外,"org.springframework.web.HttpRequestMethodNotSupportedException, message:Request method 'DELETE' not supported, path:/api/v0/customers"问题出在春天,你没有正确定义资源网址。 您可以先检查路径是否写得很好,然后在连接到前端之前使用postman调试spring应用程序。