AlertController Ionic 2 Uncaught (in promise): ins

2019-03-26 20:30发布

问题:

Instantiating the Ionic 2 AlertController on the same page it gives this error: Uncaught (in promise): inserted view was already destroyed

I would like to make it run several times equal to the ionic 1 alert instance that can be called several times on the same page.

Code:

  export class ConsultaProdutoPage {

    public usar_leitor: boolean = false;
    public codigo: string = '';
    public icon: object = { 'icon': 'search', 'text': 'Buscar' };
    public mostrar_produto: boolean = false;
    private loading;
    private _alert: Alert;

    constructor(public navCtrl: NavController,
        public navParams: NavParams,
        private _barcodeScanner: BarcodeScanner,
        private _alertCtrl: AlertController,
        private _service: consultaProdutoService,
        private _loadingCtrl: LoadingController) {

        this.loading = this._loadingCtrl.create({
            content: 'Buscando Produtos. Aguarde...',
            dismissOnPageChange: true
        });

        this._alert = this._alertCtrl.create({
            'title': "Aviso",
            'message': 'Erro ao buscar produtos.',
            buttons: ['OK']
        });

    }

    buscaProduto(codigo) {

        this.loading.present();

        this._service.getProduto(this.codigo)
            .then(success => {
                console.log(success);
            })
            .catch(err => {

                this.loading.dismiss();
                this.codigo = '';

                this._alert.present();

            });


    }

}

回答1:

This issue is because of reuse of loading object in your function.

Since you " would like to make it run several times ", the loading object is also getting reused. However this object can only be used once. Check here.

Try:

buscaProduto(codigo) {
         this.loading = this._loadingCtrl.create({
            content: 'Buscando Produtos. Aguarde...',
            dismissOnPageChange: true
        });

        this.loading.present();

        this._service.getProduto(this.codigo)
            .then(success => {
                console.log(success);
            })
            .catch(err => {

                this.loading.dismiss();
                this.codigo = '';

                this._alert.present();

            });


    }