Angular 6 - Rxjs 6 - Type Observable <object>不能分配给Observable <item>类型

时间:2018-05-23 16:08:57

标签: angular rxjs observable

将我的Angular项目从版本5更新到6后,我收到此错误:

  

输入Observable'&lt;'Object&gt;不能分配给Observable类型'&lt;'Todo&gt;。

在我的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))
    );
  }
}

错误指向addTodo,editTodo和deleteTodo方法,loadTodo没有问题,因为它分配了Observable'&lt;'Object&gt;输入到Observable'&lt;'Array&gt;类型。 我使用this link来更改导入rxjs元素的方式,但没有成功。有什么帮助吗?

1 个答案:

答案 0 :(得分:9)

httpClient方法是通用的,您必须键入响应,例如:

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

必须像这样使用:

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