【发布时间】: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