【问题标题】:Angular HTTP Service returns results buried in an object, how to add the type?Angular HTTP Service 返回结果埋在一个对象中,如何添加类型?
【发布时间】:2018-11-17 14:07:12
【问题描述】:

我有一个名为 FilmService 的 Angular 服务,它使用 HttpClient 模块从 API 获取数据。当一个组件使用这个服务时,它会得到一个Film 类型的电影数组。但是,API 将这些电影对象隐藏在 results 对象中(例如 {results: []})。我使用map 运算符来处理 Observable 并返回 results 对象。但是我的 IDE 在我的 map 函数中抱怨 results 的类型:

“对象”类型上不存在属性“结果”。

如何正确输入服务方法?

请看下面我的代码。

接口:Film.ts:

export interface Film {
  id: number;
  title: string;
}

FilmService 方法:

getMostPopular(): Observable<Film[]> {
  return this.http.get(this.apiUrl, {
    params: {
      api_key: this.apiKey,
      sort_by: 'popularity.desc'
    }
  }).pipe(
    map((films) => films.results) // Property 'results' does not exist on type 'Object'.
  );
}

【问题讨论】:

标签: angular typescript


【解决方案1】:

如果您的 api 将所有响应隐藏在同一种包装对象中,您可以定义一个通用响应类型。 HttpClient 有一个泛型类型参数(对于大多数操作),它表示返回类型。

类似这样的:

export interface ApiResponse<T> {
    results: T;
    errors: string[];
}

然后按以下方式使用它:

return this.http.get<ApiResponse<Film[]>>(...).pipe(map(response => response.results));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 2020-12-24
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多