如何识别多个可观察的返回类型

时间:2018-03-28 15:19:01

标签: angular

我打电话给API以获取产品列表。但是,如果出现错误,我的api会返回一个带有状态代码和错误消息的响应。

产品service.ts:

getAllProducts(): Observable<IProduct[] | ApiResponse> {
        return this._http.get<IProduct[]>(this._GetAllUrl)
            .do(data => console.log("All: " + JSON.stringify(data)))
            .catch(err => this.HandleError(err));
    }

API-response.ts:

export class ApiResponse {
  StatusCode: number;
  Message: string;
}

product.ts:

export interface IProduct{
    Id: number;
    Name: string;
    Category: string;
    Price: number;
}

app.component.ts:

public GetAllProducts(): Subscription {
    return this._ProductService.getAllProducts().subscribe(
      response => {
        // if response is type of Product

        // else if response is type of ApiResponse
      }
    );
  }

如果可能返回产品数组或ApiResponse,我如何确定从API返回的响应的接口/类?

2 个答案:

答案 0 :(得分:1)

添加辅助函数:

type Response = IProduct[] | ApiResponse;

const isProductsResponse = (response: Response): response is IProduct[] => {
  return Array.isArray(response);
}

const isApiResponse = (response: Response): response is ApiResponse => {
  return !Array.isArray(response);
}

在您的组件中:

  ngOnInit() {
    const response$: Observable<Response> = this._ProductService.getAllProducts()

    const apiResponse$ = response$.pipe(filter(isApiResponse));
    const products$ = response$.pipe(filter(isProductsResponse));

    products$.subscribe(// ... handle products)
    apiRespons$.subscribe(// ... handle apiReponse)
  }

答案 1 :(得分:1)

有三种功能可用于向可观察的用户发送数据 complete(): void Observer回调,用于从Observable接收完整类型的无值通知。

error(err: any): void Observer回调接收来自Observable的类型错误通知,附带错误。

next(value: T): void Observer回调接收来自Observable的类型为next的通知,值为。
在可观察执行期间,可能会对observer.next()进行无限调用,但是,当调用observer.error()observer.complete()时,执行将停止,并且不会再向订阅者传递数据。 /> 修改你的方法
如果出现错误或响应,将执行适当的代码块。

 public data=[];
    public GetAllProducts(): Subscription {
        return this._ProductService.getAllProducts().subscribe(
          response => {
               this.data=response;//do whatever you want to
                },
        error=>{
                  console.log(error);//or do whatever you want to
              }
        );
      }