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 ?
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))
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With