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

Ionic 5中点击Google Map标记调用Modal控制器报错如何解决

问题原因定位

  • 第一个错误点:marker.addListener的回调使用了普通function声明,导致回调内部的this指向被改变为marker实例,而非当前页面类的实例。你在回调内部执行let that = this时,this已经不是页面对象,自然取不到挂载在页面对象上的modalCtrl,所以触发Cannot read property 'create' of undefined报错。
  • 第二个错误点:Ionic 5的ModalController.create方法是异步方法,返回Promise,和Ionic 3的同步调用逻辑不同,不能直接拿到modal实例。

修复方案

步骤1:确认ModalController已正确注入

首先检查当前页面的构造函数,确保已经注入ModalController:

import { ModalController } from '@ionic/angular';

// 页面类的构造函数
constructor(private modalCtrl: ModalController) {
  // 其他原有逻辑
}

步骤2:修正点击回调的this指向和异步调用逻辑

直接用箭头函数保留外层this指向,同时用await处理create的异步逻辑,修正后代码如下:

// 用箭头函数作为回调,保留外层this指向页面实例
marker.addListener('click', async () => {
  console.log("station id..", this.title);
  this.station_id = this.title;
  // create是异步方法,需要await等待执行完成拿到modal实例
  const modal = await this.modalCtrl.create({
    component: BarrageDetailModalPage,
    animated: true,
    mode: 'ios',
    backdropDismiss: false,
    cssClass:'edit-modal',
    componentProps: {
      "station_id": this.title,
    }
  });
  modal.onDidDismiss().then(() => {
    this.get_user_log();
  })
  return modal.present();
});

如果习惯用链式调用不用async/await,也可以改成下面的写法:

// 在回调外面提前存正确的this指向
const that = this;
marker.addListener('click', function() {
  console.log("station id..", this.title);
  that.station_id = this.title;
  // 用then链式处理异步create
  that.modalCtrl.create({
    component: BarrageDetailModalPage,
    animated: true,
    mode: 'ios',
    backdropDismiss: false,
    cssClass:'edit-modal',
    componentProps: {
      "station_id": this.title,
    }
  }).then(modal => {
    modal.onDidDismiss().then(() => {
      that.get_user_log();
    })
    return modal.present();
  })
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:24:03