Web API返回void时订阅observable

时间:2016-11-14 20:06:33

标签: angular asp.net-core asp.net-web-api2

我有一个web api delete方法返回void

如果我没有订阅Observable,则在角度2中,将永远不会调用web api方法。 QuestionCold 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;?或者,如果上述方法是正确的,我该如何解决以下错误?

  • 构建:参数'boolean'implicity有一个'any'类型
  • 构建:参数'错误'隐含有'任何'类型
  • 构建:属性'subscribe'在类型'boolean |上不存在可观察到的“

1 个答案:

答案 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');
    });
}

如果在此更改后您的控制器仍未调用,我认为这是路由错误。