【问题标题】:Angular6 Type 'Observable<Object>' is not assignable to type 'Observable<...[]>'Angular6类型'Observable<Object>'不可分配给类型'Observable<...[]>'
【发布时间】:2018-08-06 16:22:06
【问题描述】:

我的问题的上下文:我正在尝试在我的 Angular 应用程序的打字稿部分中发出 http 请求。我只是想从我的 Python REST API 调用 localhost:5000 获取数据。

我相信解决这个问题只需要以下两个组件。我只是看不到可以更换或安装什么来解决此问题。请告诉我。

exam.model.ts

// TS class to represent coordinate data

 export class Exam {
     constructor(
      public Company: string,
      public HireDate: string, // should be changed to date
      public Title: string,
      public Location: string,
      public Degree: string,
      public yearEnteredWorkForce: string, // should be changed to date
      public OfferCostNumber: string,
      public bonus: string,
      public latitude: number,
      public longitude: number
    ) { }
  }

exam-api.service.ts

import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import {API_URL} from '../env';
import {Exam} from './exam.model';

@Injectable()
export class ExamsApiService {

  constructor(private http: HttpClient) {
  }

  private static _handleError(err: HttpErrorResponse | any) {
    return Observable.throw(err.message || 'Error: Unable to complete request.');
  }

  // GET list of public, future events
  getExams(): Observable<Exam[]> {
    return this.http
      .get(`${API_URL}/data`)
      .catch(ExamsApiService._handleError);
  }
}

这是我得到的全部错误:

ERROR in src/app/http-example/exam-api.service.ts(20,5): error TS2322:     Type 'Observable<Object>' is not assignable to type 'Observable<Exam[]>'.
  Type 'Object' is not assignable to type 'Exam[]'.
    The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
      Property 'includes' is missing in type 'Object'.

【问题讨论】:

  • 默认情况下http.get 是一个对象的可观察对象。你的方法签名说你应该返回一个 array 的 observable,它是一个不同的类型。您应该指定响应对象的类型,以便 TS 可以帮助您:angular.io/guide/http#type-checking-the-response

标签: angular typescript http httpclient


【解决方案1】:

上面提到的“考试”类不能分配给 Observable,因为类不能用作接口。

制作这样的界面:

export interface Exam {
  Company: string,
  HireDate: string,
  Title: string,
  Location: string,
  Degree: string,
  yearEnteredWorkForce: string, 
  OfferCostNumber: string,
  bonus: string,
  latitude: number,
  longitude: number

}

然后在 Observable 类型中使用它。

试试这个!!,希望这会有所帮助

【讨论】:

  • 嘿,谢谢!虽然没有工作。我仍然遇到同样的错误。
  • 是否还有其他应该进行的更改?
  • 既然他们正在使用它,为什么您认为他们还没有这种类型?这并没有告诉 OP 如何在客户端实际使用它。
  • 我认为您需要将 Observable 替换为 Observable>
  • 我认为您需要将 Observable 替换为 Observable>... 这将消除错误,并且在订阅上述接口的可观察使用时响应类型..
猜你喜欢
  • 2020-11-23
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-14
  • 2021-01-02
  • 2018-11-02
  • 2019-01-12
相关资源
最近更新 更多