Can't resolve all parameters for Storage: (?)

前端 未结 6 2157
情深已故
情深已故 2020-12-10 01:45

I am getting values from a modal and I want to store and get it using local storage in ionic2 angular2 project. My code is given below. It gives following error:

6条回答
  •  一整个雨季
    2020-12-10 02:20

    You need to move the code where you are accessing the values from a resolved promise into the .then() of that promise. Since, it is async operation, by the time you use it, it might not be available.

    E.g. this could work:

    presentModal() {
        this.storage.get('distUnit').then((val) => {
            console.log('Your distUnit is', val);
            this.DistanceUnit = val;
            this.storage.get('SetRadious').then((val) => {
                console.log('Your SetRadious is', val);
                this.selectedRadious = val;
    
                this.modalCreator();
            })
            .catch(err=>{
                console.log('Your SetRadious dont exist: ' + JSON.stringify(err));
                this.selectedRadious = 500;
                this.modalCreator();
            });
        })
        .catch(err=>{
            console.log('Your distUnit dont exist: ' + JSON.stringify(err));
            this.DistanceUnit = 'Meters';
    
            this.storage.get('SetRadious').then((val) => {
                console.log('Your SetRadious is', val);
                this.selectedRadious = val;
    
                this.modalCreator();
            })
            .catch(err=>{
                console.log('Your SetRadious dont exist: ' + JSON.stringify(err));
                this.selectedRadious = 500;
                this.modalCreator();
            });
        });
    }
    
    modalCreator(){
        let obj = {selectedRadious: this.selectedRadious, DistanceUnit: this.DistanceUnit};
        let myModal = this.modalCtrl.create(SettingModalPage, obj);
    
        myModal.onDidDismiss(data => {
            console.log('modal value: '+data.DistanceUnit)
            this.DistanceUnit = data.DistanceUnit;
            this.selectedRadious = data.selectedRadious;
    
            this.storage.set('distUnit', this.DistanceUnit);
            this.storage.set('SetRadious', this.selectedRadious);
        });
        myModal.present();
    }
    

    If you read the code carefully, you will get to know that I have handled all the cases for getting both the parameters and if one of them fails. Check it out and let me know.

提交回复
热议问题