7
votes

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 ?

1
How about trying post<Todo[]>?Reactgular
post<Todo[]> means that we post an array, can you please explain more ?Sami-L
Using post<Todo[]> would mean the post request would return a Todo array. What you post in the body wouldn't matter or change.Jun Kang
Try casting the post, put and delete method with <Todo>. E.g: http.post<Todo>()Chau Tran
Like what you did with your get method, do the same for everything else but with Todo instead of Todo[]Chau Tran

1 Answers

12
votes

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