IonicNg modalController在openlayers监听器中未定义。

问题描述 投票:0回答:1

我试图在选择openlayers功能时打开一个离子模式。我已经注入了ModalController,但当它从监听器中使用时,它是未定义的。我认为这是因为上下文不同,但我如何解决这个问题?我应该使用eventEmitters或rxobservables,还是可以正确地连接监听器?下面是代码

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ModalController } from '@ionic/angular';
    import { SelectActionNichoirPage } from '../../pages/modal/select-action-nichoir/select-action-nichoir.page';

    @Component({
    selector: 'app-openlayers-wrapper',
    templateUrl: './openlayers-wrapper.component.html',
    styleUrls: ['./openlayers-wrapper.component.scss'],
    })
    export class OpenlayersWrapperComponent implements OnInit {
    selectClick;

    constructor(public modalController: ModalController) {
    console.log("Construct modal" , this.modalController); // not Undefined
    }

    initMap() {

    this.map = new OlMap({
      target: 'map',
      layers: [this.layer, observationsVectorLayer],
      view: this.view,
    });

    this.selectClick = new Select({
        condition: click
      });
    this.map.addInteraction(this.selectClick);

    console.log("add listen", this.modalController); // not undefined
    this.selectClick.on('select', function(e) {
       console.log(e.target.getFeatures().getLength() +
            ' selected features');
       console.log("modal ctrl in listener", this.modalController); // UNDEFINED
        });
    this.selectClick.on('select', this.presentModal); 
    }

    async presentModal() {
       console.log("modal ctrl in function", this.modalController);  // UNDEFINED
       const modal = await this.modalController.create({             // exception : no method create on undefined
         component: SelectActionNichoirPage
       });
       return await modal.present();
     }
    }

ionic-framework openlayers angular8 ionic5
1个回答
1
投票

对于一个快速的修复方法,也可以帮助你确认你对问题的直觉,在声明函数之前保存一个对你的组件的引用,类似这样。

var self = this;
this.selectClick.on('select', function(e) {
    console.log(e.target.getFeatures().getLength() +
        ' selected features');
    console.log("modal ctrl in listener", self.modalController); // <- self
    self.presentModal(); <- self
});
© www.soinside.com 2019 - 2024. All rights reserved.