You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular回调函数内无法设置变量问题求助

解决Google Maps DirectionsService赋值为空的问题

嘿,这个问题我太熟了!你猜的没错,核心问题确实和作用域以及异步操作有关,让我一步步帮你搞定:

1. 先解决this指向的问题

你代码里的回调用了箭头函数,理论上this应该继承外层上下文,但有时候在类组件或者特定环境下,外层的this指向可能还是出问题。保险起见,可以用两种方式确保this指向正确:

方式一:保存this的引用

在回调外部先把当前实例的this存起来,回调里用这个引用赋值:

this.mapsAPILoader.load().then(() => {
  const self = this; // 保存当前组件/类实例的引用
  const p1 = new google.maps.LatLng(50.926217, 5.342043);
  const p2 = new google.maps.LatLng(50.940525, 5.353626);
  const directionsService = new google.maps.DirectionsService();
  const request = {
    origin: p1,
    destination: p2,
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
  };
  
  directionsService.route(request, (response, status) => {
    if (status === google.maps.DirectionsStatus.OK) {
      const point = response.routes[0].legs[0];
      console.log(point.duration.text);
      self.travelTimeDriving = point.duration.text; // 用self代替this,确保指向正确
    }
  });
});

方式二:用箭头函数定义外层方法

如果这段代码是类的方法,直接用箭头函数定义方法,确保方法内部的this始终指向类实例:

// 类中的方法定义
calculateTravelTime = () => {
  this.mapsAPILoader.load().then(() => {
    // 你的原有代码放在这里,this指向会自动正确
  });
}

2. 注意异步执行的时机

directionsService.route是异步操作,回调函数要等API请求完成后才会执行。如果你在调用route之后马上访问this.travelTimeDriving,那时候回调还没触发,变量自然是空的!

比如下面的代码就会拿到空值:

this.calculateTravelTime();
console.log(this.travelTimeDriving); // 空值,因为回调还没执行

解决办法是:把需要使用travelTimeDriving的逻辑放到回调函数内部,或者把route封装成Promise,用async/await等待结果。

3. 封装Promise让代码更优雅

既然Google Maps没提供Promise版本的API,我们自己封装一个,这样就能用then或者async/await处理异步,代码更清晰:

// 封装Promise版的DirectionsService.route
const fetchDirections = (request) => {
  return new Promise((resolve, reject) => {
    const directionsService = new google.maps.DirectionsService();
    directionsService.route(request, (response, status) => {
      if (status === google.maps.DirectionsStatus.OK) {
        resolve(response);
      } else {
        reject(new Error(`获取路线失败:${status}`));
      }
    });
  });
};

// 使用async/await调用
this.mapsAPILoader.load().then(async () => {
  const p1 = new google.maps.LatLng(50.926217, 5.342043);
  const p2 = new google.maps.LatLng(50.940525, 5.353626);
  const request = {
    origin: p1,
    destination: p2,
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
  };
  
  try {
    const response = await fetchDirections(request);
    const point = response.routes[0].legs[0];
    this.travelTimeDriving = point.duration.text;
    // 在这里处理travelTimeDriving的后续逻辑,比如更新页面
  } catch (err) {
    console.error(err);
  }
});

这样既解决了作用域问题,又能清晰处理异步流程,还能捕获错误~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:19:42