简体   繁体   English

如何在打字稿中使用地图操作符上的类型?

[英]How to use a type on map operator in typescript?

Basically, I am trying to use HttpClient instead of Http on all my calls, so I created an interface to be able to access some properties of the response, it is working fine for most of my calls; 基本上,我试图在所有调用中使用HttpClient而不是Http,因此我创建了一个接口,以便能够访问响应的某些属性,对于大多数调用而言,它都可以正常工作; but the thing is that I have a typeahead with this code: 但问题是我用以下代码提前输入了:

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

I tried to assign my interface called APIResponse to response on the last two lines, like this: .map(response:APIResponse => ...) , but it obviously throws a syntax error. 我试图将名为APIResponse的接口分配给最后两行的response ,如下所示: .map(response:APIResponse => ...) ,但显然会引发语法错误。

Where should I include the type for response? 我应该在哪里添加响应类型? Or how could I change my code to do so? 或者我该如何更改我的代码?

Thanks in advance. 提前致谢。

Personally, I'd do: 就个人而言,我会:

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

BTW, if you were to use the new HttpClient introduced in angular 4.3, you wouldn't need to convert to JSON manually and could simply write: 顺便说一句,如果您要使用在angular 4.3中引入的新HttpClient ,则无需手动转换为JSON,只需编写即可:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM