Angular中的地址搜索栏,可以看到带有建议的网址

问题描述 投票:0回答:2
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)
      );
  }
}

我正在建立一个自动完成的搜索栏,以获取Angular中的地址建议。地址建议来自URL中的第三方提供商。我无法从Observable响应中提取特定密钥。该键名为候选对象。是否可以在服务时从“可观察到的响应”中仅提取密钥? github repo

angular service autocomplete rxjs esri
2个回答
1
投票

使用地图运算符将响应转换为其他内容。

为您的回复创建类型是一个好主意。vs代码中的代码完成将使您更轻松。


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


0
投票
  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);
    };
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.