【问题标题】:Address Search Bar in Angular with Observable to url with recommendationsAngular 中的地址搜索栏,可观察到带有推荐的 URL
【发布时间】:2020-07-22 12:51: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)
      );
  }
}

我正在为 Angular 中的地址建议构建一个自动完成的搜索栏。地址建议来自 URL 中的第三方提供商。我无法从 Observable 响应中提取某个键。该键名为Candidates。是否可以从服务中的可观察响应中仅提取密钥? github repo

【问题讨论】:

    标签: angular service autocomplete rxjs esri


    【解决方案1】:

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

    为您的回复创建类型是个好主意。 它会让你在 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)
          );
      }
    }
    
    

    【讨论】:

    • 就是这样!下面的最终解决方案
    【解决方案2】:
      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);
        };
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-27
      • 1970-01-01
      • 2020-08-28
      • 2021-05-02
      • 1970-01-01
      • 2021-08-31
      • 2021-06-10
      • 2016-08-26
      • 2018-07-20
      相关资源
      最近更新 更多