2016-05-16 74 views
2

我想避免在我的打字稿angularjs代碼中使用<any>。 因此,我想知道是否有人知道哪些類類型應該用於$ http get/post/etc。響應?

實施例:在下面的代碼段我想<any>待類類型代替

search() { 
    this.$http.get('https://maps.googleapis.com/maps/api/geocode/json', {params: {address: this.$scope.searchTerm}}) 
    .success((response: any) => { 
     this.$scope.results = response.results; 
    }).error((response: any) => { 
     console.error("Error calling the server"); 
     }); 
    }; 

PS:

此$範圍= MyScopeInterface和這個$ scope.results =谷歌。 maps.GeocoderResult

回答

1

您不需要手動鍵入它。 Typescript的類型推斷應能夠相應地確定.get()的返回類型和response參數的類型。

如果不是,則類型爲IHttpPromise<T>。你可以找到更多的細節angular.d.ts type declaration

+0

我正在編寫和編譯我的代碼在Webstorm。似乎此編譯器無法確定返回類型(錯誤:(77,40))TS2339:屬性「結果」在類型「{}」上不存在)。仍在試圖弄清楚,然後在我的情況,我應該是(?) –

+0

'IHTTPPromise '延伸'IPromise >'這意味着它是一個包含HTTP響應ARG它本身含有的一些數據''一個承諾作爲有效載荷。 ''是有效載荷的類型,所以無論從服務器返回什麼。 [地理編碼api頁面](https://developers.google.com/maps/documentation/geocoding/intro#GeocodingResponses)有一個示例JSON響應。您可以構建一個接口來匹配該對象,或者其他人可能已經在地理編碼訪問庫中。 – Paarth

+0

我做到了,解決了我的問題: '/// <參考路徑= 「../../分型/ tsd.d.ts」/> 模塊服務{ 導出接口IGeocoder { 結果:谷歌.maps.GeocoderResult []; status:google.maps.GeocoderStatus; } }' –