How to display data form http request in alert in ionic


#1

I am trying to display a data from http request and display it in alert
but all I get is [object object] and in my console, I can see my data [{code: “MNV”}] but I
don’t know how I can make display in the alert

public Code:any;

 Coupons(offer,code){
this.peopleservice.getCoupons(offer,code).subscribe(data=>this.Code=data);
       let prompt = this.alertCtrl.create({

             title: 'code',
             message:this.Code,

             buttons:[
                 {
                    text: 'Cancel',
      handler: data => {

        console.log(this.Code)

                 }
                 }
             ]
        }

        );
        prompt.present();

#2

maybe because it is asynchronous, try console.log before creation of the prompt


#3

In the first try I got undefined in the console and an empty alert and in
the second try the I got [{code: “MNV”}] in the console and an [object object ] in the alert


#4

You have two problems. First is what @FnnHuman was alluding to, which is that you must move the creation of the alert inside the subscription in order to be able to rely on code being set. Secondly, you are responsible for converting the object into a string before you pass it as a message.


#5

thank you both so much it did work ,but I still have one more problem with is that is alert I get is [{code: “MNV”}] how can I get only MNV


    Coupons(offer,code){
  this.peopleservice.getCoupons(offer,code)
  .subscribe( data => { this.Code = JSON.stringify(data)

        let prompt = this.alertCtrl.create({
            title: 'code',
            message: this.Code, 
            buttons:[
                {
                    text: 'Cancel',
                    handler: data => {

                    }
                }
            ]
        });
        prompt.present();

    });

#6

Replace this with data.code.


#7

it didn’t work the alert is empty !!


#8

If you are positive that data is going to be a one-element array, data[0].code should work.


#9

Yes It did work perfectly

 Coupons(offer,code,Store){

    
  this.peopleservice.getCoupons(offer,code,Store)
  .subscribe(data =>{this.Coode = data[0].code
  
    let prompt = this.alertCtrl.create({
            title: 'code',
            message: this.Code, 
            buttons:[
                {
                    text: 'Cancel',
                    handler: data => {

                    }
                }
            ]
        })
        prompt.present();


},resError=>this.dataError(2));

}