11
votes

I am new to typescript, and I get this error

Type 'Observable' is not assignable to type 'IProduct[]'. Property 'includes' is missing in type 'Observable'.

My service class is :

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)
}

Where is it wrong and what should I do to fix it?

3
show the _http.get function. Seems like it returns a value of observable instead of observable.elzoy
How does your receiving component code look like?AJT82
Use function binding in cases like above because it allows the function to be called with clearer context. Though, current code will also work fine but using bind is a good practice. thenewstack.io/mastering-javascript-callbacks-bind-apply-callManu Bhardwaj

3 Answers

18
votes

If this question comes from the Angular course on Pluralsight by @DeborahKurata, the answer is in the next module, "Subscribing to an Observable".

In the ngOnInit(): void method in product-list.component.ts, change this

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

to

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

Looks like http.get<IProduct[]>(this._productUrl) returns an array of IProduct and your code tries to return it as an observable IProduct array. To return an observable array from your getProducts function (using RxJS), you could do this:

import { Observable } from 'rxjs';

return observable.of(this._http.get<IProduct[]>(this._productUrl));
0
votes

In case you also come from pluralsight - Angular Component Communication.

After you perform the change from K0D4 answer.

At the product.service.ts replace the ErrorObservable with throwError:

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

Then at the bottom, the handleError does not return ErrorObservable, you can use throwError:

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

I started getting the Observer errors after updating to Angular 7, and it was because of this.