【问题标题】:How to use a type on map operator in typescript?如何在打字稿中使用地图运算符上的类型?
【发布时间】:2017-10-22 15:11:59
【问题描述】:

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

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 的接口分配给 response,如下所示:.map(response:APIResponse => ...),但它显然会引发语法错误。

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

提前致谢。

【问题讨论】:

  • this.http.get<ApiResponse>(...),那么就可以去掉.json()的映射。你没看the docs吗?
  • 您的标签显示您正在使用HttpClient,但在使用Http 时可以使用json() 方法。你用的是哪个?也就是this.http的类型是什么?

标签: angular typescript httpclient


【解决方案1】:

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

.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);

【讨论】:

    【解决方案2】:

    如果添加类型需要使用():

    .map((response:APIResponse) => ...)
    

    【讨论】:

    • 这是一种危险的做法,应该避免。原因是,如果将 api 键入为Observable &lt;any&gt;,这种形式会产生一种类型安全的错误错觉,这种错觉随时可能被破坏,尤其是在链式操作符调用中。相反,如果 API 具有正确的参数类型,那么显式指定一个也是一种不好的做法,因为这又会导致误导性代码。
    猜你喜欢
    • 2022-07-21
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2018-07-25
    • 2018-06-01
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多