Reputation: 17
export class AddressSuggestionsService {
private addressSuggestionsUrl =
'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?f=json&singleLine=';
constructor(private httpClient: HttpClient) {}
getAddressSuggestions(term: string): Observable<any> {
return this.httpClient
.get(
`${this.addressSuggestionsUrl}${term}&outfields=Match_addr,Addr_type=PointAddress`
)
.pipe(
tap((data) => console.log('All: ' + JSON.stringify(data))),
catchError(this.handleError)
);
}
}
I'm building out an auto-complete Search Bar for address suggestions in Angular. Address-Suggestions come from a third party provider in URL. I'm having trouble extracting a certain key from the Observable response. The key is named Candidates. Is it possible to extract only key from an Observable Response at service? github repo
Upvotes: 0
Views: 193
Reputation: 17
searchAddress(term: string): Observable<Address[]> {
let url = `${this.endpoint}${term}&maxLocations=5&location=30.270,-97.745&distance=80467.2`;
if (!term.trim()) {
return of([]);
}
return this.httpClient
.get<Address[]>(url)
.pipe(
map((data) => data['candidates']),
catchError(this.handleError<Address[]>('addresses', []))
);
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.log(`failed: ${error.message}`);
return of(result as T);
};
}
}
Upvotes: 0
Reputation: 7682
use the map operator to convert the response into something else.
It's a good idea to create types for your responses. it will make it easier for you with code completion in vs code.
interface AddressSuggestionResponse {
Candidates: string[]
}
export class AddressSuggestionsService {
private addressSuggestionsUrl =
'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?f=json&singleLine=';
constructor(private httpClient: HttpClient) {}
getAddressSuggestions(term: string): Observable<string[]> {
return this.httpClient
.get<AddressSuggestionResponse>(
`${this.addressSuggestionsUrl}${term}&outfields=Match_addr,Addr_type=PointAddress`
)
.pipe(
map((data) => data.Candidates),
catchError(this.handleError)
);
}
}
Upvotes: 1