Angular6类型'Observable <object>'不能分配给类型'Observable <... []>'

时间:2018-08-06 16:22:07

标签: angular typescript http httpclient

我的问题的上下文:我正在尝试在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'.

1 个答案:

答案 0 :(得分:0)

如上所述,“考试”类无法分配给Observable,因为不能将类用作接口。

创建这样的界面:

file.js

}

然后以可观察类型使用它。

尝试!!,希望对您有所帮助