类型'Observable <product [] | =“”order =“”>'不能分配给'Observable <product []>'

时间:2018-05-27 09:19:47

标签: angular typescript

这来自“Pro_Angular”一书,第8章。

getProducts(): Observable<Product[]> {
    return this.sendRequest(RequestMethod.Get, "products");
}

saveOrder(order: Order) : Observable<Order> {
    return this.sendRequest(RequestMethod.Post, "orders", order);
}

private sendRequest(verb: RequestMethod,
   url: string, body?: Product | Order): Observable<Product[] | Order> {
       return this.http.request(new Request({
           method: verb,
           url: this.baseUrl + url,
           body: body
       })).map(response => response.json())
}

警告信息为:

[ts]Type 'Observable<Product[] | Order>' is not assignable to type 'Observable<Product[]>'.
Type 'Product[] | Order' is not assignable to type 'Product[]'.
Type 'Order' is not assignable to type 'Product[]'.
Property 'length' is missing in type 'Order'.

[ts]Type 'Observable<Product[] | Order>' is not assignable to type 'Observable<Order>'.
Type 'Product[] | Order' is not assignable to type 'Order'.
Type 'Product[]' is not assignable to type 'Order'.
Property 'id' is missing in type 'Product[]'.

这个问题似乎是由OR(|)运算符引起的。我想知道如何使sendRequest()的主体采用多个参数(此处为ProductOrder)。

1 个答案:

答案 0 :(得分:0)

您可以将变量设置为以下类型:

Observable<Product[]> | Observable<Order>

我相信它正在寻找一种Product[] | Order,我不确定这是否是一种有效的类型。