angular - 如何在 typescript 中使用 map 运算符上的类型?

标签 angular typescript httpclient

基本上,我试图在我的所有调用中使用 HttpClient 而不是 Http,因此我创建了一个接口(interface)来访问响应的某些属性,它对我的​​大多数调用都工作正常;但问题是我提前输入了这段代码:

const URL = 'https://maps.google.com/maps/api/geocode/json';
this.searchField = new FormControl();
this.results$ = this.searchField.valueChanges
    .debounceTime(500)
    .switchMap(query => this.http.get(`${URL}?address=${query}`))
    .map(response => response)
    .map(response => response.results);

我试图在最后两行将名为 APIResponse 的接口(interface)分配给 response,如下所示:.map(response:APIResponse => ...),但是它显然会引发语法错误。

我应该在哪里包含响应类型?或者我该如何更改我的代码才能这样做?

提前致谢。

最佳答案

就我个人而言,我会这样做:

.map(response => response.json() as ApiResponse)
.map(response => response.results);

顺便说一句,如果您要使用 Angular 4.3 中引入的新 HttpClient,则无需手动转换为 JSON,只需编写:

this.httpClient.get<ApiResponse>(`${URL}?address=${query}`
    .map(response => response.results);

关于angular - 如何在 typescript 中使用 map 运算符上的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46875647/

相关文章:

Angular 7 没有缩小 html、js、css 文件

angular - 更新 TSLint 错误 : Could not find implementations for the following rules specified in the configuration

javascript - &lt;input type =“text” maxlength =“4” > 不应将逗号和点计入 maxlength

java - Secure iNet Factory 和 Apache httpclient,哪个更强大?

javascript - 在所有类/接口(interface)/函数前面加上 App 首字母缩略词是个好习惯吗?

angular - 相当于组件功能的路由守卫

angular - 循环遍历@ViewChildren 原生元素

reactjs - 使用 React 和 TypeScript 动态渲染组件

java - Java 中的 REST API 调用

c# - 有没有办法清除 CookieContainer?