执行“ng build”命令时发生错误:
ERROR in src/app/model/rest.datasource.ts(34,5): error TS2322: Type 'Observable<Product | Order | Product[] | Order[]>' is not assignable to type 'Observable<Product[]>'.
Type 'Product | Order | Product[] | Order[]' is not assignable to type 'Product[]'.
文件rest.datasource.ts:
import { Injectable } from '@angular/core';
import { Http, Request, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Product } from './product.model';
import { Cart } from './cart.model';
import { Order } from './order.model';
import 'rxjs/add/operator/map';
const PROTOCOL = 'http';
const PORT = 3500;
@Injectable()
export class RestDataSource {
baseUrl: string;
auth_token: string;
constructor(private http: Http) {
this.baseUrl = `${PROTOCOL}://${location.hostname}:${PORT}/`;
}
authenticate(user: string, pass: string): Observable<boolean> {
return this.http.request(new Request({
method: RequestMethod.Post,
url: this.baseUrl + 'login',
body: {name: user, password: pass}
})).map(response => {
let r = response.json();
this.auth_token = r.success ? r.token : null;
return r.success;
});
}
getProducts(): Observable<Product[]> {
return this.sendRequest(RequestMethod.Get, 'products');
}
saveProduct(product: Product): Observable<Product> {
return this.sendRequest(RequestMethod.Post, 'products', product, true);
}
updateProduct(product): Observable<Product> {
return this.sendRequest(RequestMethod.Put, `products/${product.id}`, product, true);
}
deleteProduct(id: number): Observable<Product> {
return this.sendRequest(RequestMethod.Delete, `products/${id}`, null, true);
}
getOrders(): Observable<Order[]> {
return this.sendRequest(RequestMethod.Get, 'orders', null, true);
}
deleteOrder(id: number): Observable<Order> {
return this.sendRequest(RequestMethod.Delete, `orders/${id}`, null, true);
}
updateOrder(order: Order): Observable<Order> {
return this.sendRequest(RequestMethod.Put, `orders/${order.id}`, order, true);
}
saveOrder(order: Order): Observable<Order> {
return this.sendRequest(RequestMethod.Post, 'orders', order);
}
private sendRequest(verb: RequestMethod, url: string, body?: Product | Order, auth: boolean = false)
: Observable<Product | Product[] | Order | Order[]> {
let request = new Request({
method: verb,
url: this.baseUrl + url,
body: body
});
if (auth && this.auth_token != null) {
request.headers.set('Authorization', `Bearer<${this.auth_token}>`);
}
return this.http.request(request).map(response => response.json());
}
}
终端错误: Error TS2322
帮助我理解,这是代码中的错误还是编译错误?
PS:执行“ng serve”命令时发生此错误,但在rest.datasource.ts文件中保存更改后,webpack编译并运行应用程序
答案 0 :(得分:0)
您的方法sendRequest
会返回几种类型:
Observable<Product | Product[] | Order | Order[]>
在您的组件中,您可能声明了一个变量,它将保存结果:
myvar: Product[];
但你应该做的是
myvar: Product | Product[] | Order | Order[];
您的错误来自于您的变量可以包含多种类型的数据,但您只能覆盖一种。