How to display data form http request in alert in ionic

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();

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

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

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.

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();

    });

Replace this with data.code.

it didn’t work the alert is empty !!

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

1 Like

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));

}