Angular 正在从 HttpModule 转换为 HttpClientModule 并弃用前者,详见 Difference between HTTP and HTTPClient in angular 4? .
但是 Angular 教程位于 https://angular.io/tutorial/toh-pt6使用 HttpModule,而基本信息位于 https://angular.io/guide/http使用 HttpClientModule,详见 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 将 JSON 响应解析为对象,但它不知道该对象的形状。因此,您可以指定响应的类型:
return this.http
.get<{ data: Hero[] }>(`api/heroes/?name=${term}`)
.map(res => res.data);
请注意,您可以为此创建接口(interface):
interface ItemsResponse {
data: Hero[];
}
return this.http
.get<ItemsResponse>(`api/heroes/?name=${term}`)
.map(res => res.data);
如果您怀疑什么类型的响应将是或不想创建接口(interface),那么只需使用any
:
return this.http
.get<any>(`api/heroes/?name=${term}`)
.map(res => res.data);
另见
关于angular - 从 HttpModule 转换为 HttpClientModule,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46331474/