类型 'Observable<IProduct[]>' 中缺少属性'includes'



我是typescript的新手,我得到了这个错误

类型"Observable"不可分配给类型"IProduct[]"。类型"Observable"中缺少属性"includes"。

我的服务类别是:

getProducts() : Observable<IProduct[]> {
return this._http.get<IProduct[]>(this._productUrl)
.do(data=>console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}

private handleError(err : HttpErrorResponse){
console.log(err.message);
return Observable.throw(err.message)
}

哪里出了问题,我该怎么办才能解决?

如果这个问题来自@DeborahKurata关于Pluralsight的Angular课程,答案在下一个模块"订阅Observable"中。

在product-list.component.ts中的ngOnInit(): void方法中,更改

this.products = this._productService.getProducts();
this.filteredProducts = this.products;

this._productService.getProducts()
.subscribe(products => { 
this.products = products; 
this.filteredProducts = this.products; 
}, error => this.errorMessage = <any>error);

看起来http.get<IProduct[]>(this._productUrl)返回了一个IProduct数组,而您的代码试图将其作为可观察的IProduct数组返回。要从getProducts函数(使用RxJS(返回可观察数组,可以执行以下操作:

import { Observable } from 'rxjs';
return observable.of(this._http.get<IProduct[]>(this._productUrl));

如果您也来自pluralsight-Angular Component Communication。

从K0D4开始执行更改后,回答。

在product.service.ts中,将ErrorObservable替换为throwError:

import { Observable, throwError } from 'rxjs/';

然后在底部,handleError不返回ErrorObservable,您可以使用throwError:

private handleError(err: HttpErrorResponse) {
....
return throwError(errorMessage);
}

在更新到Angular 7之后,我开始出现Observer错误,正是因为这个原因。

相关内容

最新更新