我有一个web api delete方法返回void
如果我没有订阅Observable,则在角度2中,将永远不会调用web api方法。 Question和Cold vs Hot observables。由于需要返回一个observable和subscribe,我试图返回一个Observable:
Service.ts
public deleteProduct = (product: ProductApi): Observable<boolean> | boolean => {
this._http.delete(this.actionUrl + product.productId)
.catch((error:boolean) => Observable.throw(false));
return true;
}
Component.ts
deleteProduct(product: ProductApi, event: any): void {
event.stopPropagation();
this.productApiService
.deleteProduct(product)
.subscribe((boolean) => {
this.products = this.products.filter(p => p !== product);
if (this.selectedProduct === product) { this.selectedProduct = null; }},
error => console.log(error),
() => {
console.log('ProductApiService:Delete completed');
});
}
controller.cs
// DELETE api/product/5
[HttpDelete("{id}")]
public void Delete(int id)
{
_productService.DeleteProduct(id);
}
或者有办法返回Observable&lt;'void'&gt;?或者,如果上述方法是正确的,我该如何解决以下错误?
答案 0 :(得分:2)
为什么需要在删除请求中捕获? 您可以在订阅时将错误逻辑添加到错误功能。
public deleteProduct(product: ProductApi): Observable<any> {
return this._http.delete(this.actionUrl + product.productId);
}
然后
deleteProduct(product: ProductApi, event: any): void {
event.stopPropagation();
this.productApiService
.deleteProduct(product)
.subscribe(
response => {
this.products = this.products.filter(p => p !== product);
if (this.selectedProduct === product){
this.selectedProduct = null;
}},
error => console.log(error),
() => {
console.log('ProductApiService:Delete completed');
});
}
如果在此更改后您的控制器仍未调用,我认为这是路由错误。