Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Rxjs 6 - Type Observable<Object> is not assignable to type Observable<Item>

After updated my Angular project from version 5 to 6 I got this error:

Type Observable'<'Object> is not assignable to type Observable'<'Todo>.

in my todo.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Todo } from '../../../models/Todo';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import 'rxjs/add/observable/throw';

@Injectable()
export class TodoService {

  todos: Todo[];

  constructor( private httpClient: HttpClient ) { }

  loadTodos(): Observable<Todo[]> {
    return this.httpClient.get<Todo[]>(`${environment.api}${environment.path}`).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }

  addTodo(todo: Todo): Observable<Todo> {
    return this.httpClient.post(`${environment.api}${environment.path}`, JSON.stringify(todo)).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }

  editTodo(todo: Todo): Observable<Todo> {
    return this.httpClient.put(`${environment.api}${environment.path}/${todo.id}`, JSON.stringify(todo)).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }

  deleteTodo(todo: Todo): Observable<Todo> {
    return this.httpClient.delete(`${environment.api}${environment.path}/${todo.id}`).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }
}

The error points to addTodo, editTodo, and deleteTodo methods, loadTodo has no issues since it assigns Observable'<'Object> type to Observable'<'Array> type. I used this link to change the way rxjs elements are imported, but without success. Any help ?

like image 676
Sami-L Avatar asked May 23 '18 16:05

Sami-L


1 Answers

httpClient methods are generic, you have to type the response, for example:

    addTodo(todo: Todo): Observable<Todo> {
        return this.httpClient.post(`${environment.api}${environment.path}`, JSON.stringify(todo)).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }

has to be used like this:

    addTodo(todo: Todo): Observable<Todo> {
    return this.httpClient.post<Todo>(`${environment.api}${environment.path}`, JSON.stringify(todo)).pipe(
      catchError((error: any) => Observable.throw(error))
    );
  }
like image 180
Sergi Dote Teixidor Avatar answered Oct 18 '22 18:10

Sergi Dote Teixidor