如何在RxJS Observable上调用next和error

时间:2020-01-23 11:48:01

标签: angular rxjs graphql observable

如果您的API(例如GraphQL)允许正常失败,并且同时返回了dataerror,那么有一种方法可以同时调用Observable的happy和error路径。

服务:

public fetchData: Observable<any> {
    return myApi.fetch().pipe(map(result => {
        if (result.data) {
            // call happy path here
        }   
        if (result.error) {
            // call error path (as well) here
        } 
    }));
}

呼叫者:

myService.fetchData().subscribe(
    next => {
        // this is called
    }, error => { 
        // as well as this
    });

是否有一种整洁的方法来管道/映射结果并调用两个回调函数?

2 个答案:

答案 0 :(得分:1)

您可以将fetchData函数包装在Observable中。

服务:

public fetchData: Observable<any> {
    return new Observable(observer => {
        myApi.fetch().subscribe(
            result => {
                observer.next(result.data); // call happy path here
                if (result.error) {
                    observer.error(result.error); // call error path (as well) here
                }
            }
        );
    });
}

StackBlitz DEMO

答案 1 :(得分:0)

听起来好像您希望能够在API返回错误时从提取中获取返回给调用者的值。您可以尝试这样的事情

myService.fetchData().subscribe(response => {
  if(!response) {
    // error state
  }
  // success state
});

catchError将捕获所有错误响应,然后将返回Observable。然后在呼叫者中您可以执行以下操作

List<Product> products = [
{
  "ProductID":"1234",
  "ProductName":"Milk",
  "ProductCategory":"Dairy",
},
{
  "ProductID":"12345",
  "ProductName":"Apple",
  "ProductCategory":"Fruits",
},{
  "ProductID":"12342",
  "ProductName":"Chicken",
  "ProductCategory":"Meat",
},{
  "ProductID":"123422",
  "ProductName":"Eggs",
  "ProductCategory":"Dairy",
},
{
  "ProductID":"1234222",
  "ProductName":"Bread",
  "ProductCategory":"Dairy",
}


];