从 HttpModule 转换为 HttpClientModule

Converting from HttpModule to HttpClientModule

Angular 正在从 HttpModule 转换为 HttpClientModule 并弃用前者,详见

但是 Angular 教程位于 https://angular.io/tutorial/toh-pt6 uses HttpModule, while the Fundamentals information at https://angular.io/guide/http uses HttpClientModule as detailed at https://github.com/angular/angular/issues/19280。本教程使用内存服务器,而基础知识使用真实的 Web 服务器,这使得比较变得更加困难。

我尝试使用真实的 Web 服务器在 Angular 教程代码中从 HttpModule 切换到 HttpClientModule,并且使某些部分工作但其他部分不工作。将 hero.services.ts 中的一种 getHeroes 方法从

更改似乎可行
  getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
      .toPromise()
      .then(response => response.json().data as Hero[])
      .catch(this.handleError);
  }

  getHeroes(): Promise<Hero[]> {
    return this.httpClient.get(this.heroesUrl)
      .toPromise()
      .then(data => data['heroes'] as Hero[])
      .catch(this.handleError);
  }

尽管可能有改进的方法,而且此版本可能存在我尚未发现的问题。

但我没有在 hero-search.service.ts

中看到搜索方法的等效项
  search(term: string): Observable<Hero[]> {
    return this.http
      .get(`api/heroes/?name=${term}`)
      .map(response => response.json().data as Hero[]);
  }

应该可以省去map,但是你不能用上面的方法,因为有一个Observable而不是Promise,你会得到如下错误:

Type 'Observable<Object>' is not assignable to type 'Observable<Hero[]>'.

有没有人把Angular教程中的Heroes demo转换为使用HttpClientModule或者知道如何转换上面的搜索代码?

重写他们在 httpClient 中删除 response.json 的组件,不再需要调用 response.json()。如果数据不是响应的正确名称,请打开控制台并查找 return 对象的正确名称。

search(term: string): Observable<Hero[]> {
return this.http
  .get(`api/heroes/?name=${term}`)
  .map(response => {
         console.log(response);
         return response['data'] as Hero[]
   });

}

虽然 HttpClient 将 JSON 响应解析为对象,但它不知道该对象的形状。所以你可以指定响应的类型:

return this.http
    .get<{ data: Hero[] }>(`api/heroes/?name=${term}`)
    .map(res => res.data);

请注意,您可以为此创建接口:

interface ItemsResponse {
  data: Hero[];
}

return this.http
  .get<ItemsResponse>(`api/heroes/?name=${term}`)
  .map(res => res.data);

如果您不确定或不想创建界面的响应类型,则只需使用 any:

return this.http
  .get<any>(`api/heroes/?name=${term}`)
  .map(res => res.data);

TOH-HttpClientModule Example

另见