You need to enable JavaScript to run this app. Angular通过Jsonp调用HERE Geocoder Autocomplete API回调错误如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Angular通过Jsonp调用HERE Geocoder Autocomplete API回调错误如何解决?

问题原因

  • 核心原因是HERE Geocoder Autocomplete API的JSONP回调参数名不是你使用的callback,而是jsoncallback。你的请求里传的是callback=ng_jsonp_callback_0,API无法识别这个参数,就会直接返回纯JSON结构,不会用回调函数包裹返回内容,浏览器拿到响应后找不到要执行的回调函数,就会抛出对应错误。
  • 次要原因是你直接拼接查询参数,没有对query内容做URL编码,当查询内容包含空格、特殊符号时,会导致参数解析异常,也可能触发这类问题。

解决方法

  1. 把Angular jsonp调用的第二个参数从callback改为jsoncallback,对齐API要求的回调参数名
  2. 使用HttpParams构造查询参数,自动处理URL编码,避免特殊字符导致的参数异常
  3. 修改后的服务代码参考如下:
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LocationService {

  constructor(
    private http: HttpClient,
  ) { }

  public getSuggestions(query: string): Observable<Suggestion[]> {
    const params = new HttpParams()
      .set('query', query)
      .set('beginHighlight', '<b>')
      .set('endHighlight', '</b>')
      .set('apiKey', environment.hereDevelopper.key);
    
    const url = environment.hereDevelopper.suggestionAPIURL;
    // 第二个参数改为API要求的jsoncallback
    return this.http.jsonp<Suggestion[]>(url + '?' + params.toString(), 'jsoncallback')
      .pipe(map(suggestions => suggestions));
  }
}

内容的提问来源于stack exchange,提问作者beurre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 06:15:02