I'm trying to show an alert message using ToastController in Ionic2. The message data is coming from server with PHP code. I'm having trouble retrieving the text from the PHP file into my ToastController. The message alert only shows up when I define it manually on the controller itself.
PHP:
if($db){
$query = "SELECT * FROM cliente WHERE rut='$rut'";
$data=mysqli_query($db,$query);
if($fila=mysqli_fetch_assoc($data))
{
$datos = array("mensaje" => "no fue posible insertar datos");
echo json_encode($datos);
}else{
$sql2 = "insert into cliente values('".$rut."','".$nombre."','".$apellido."','".$correo."','".$pass."')";
$query = $db->prepare($sql2);
$query ->execute();
$sql3 = "insert into carrito values(NULL,'".$rut."')";
$query = $db->prepare($sql3);
$query ->execute();
$datos = array("mensaje" => "Registrado correctamente");
echo json_encode($datos);
}
}
else{
$datos = array("mensaje" => "No hay conexion.");
echo json_encode($datos);
};
.TS file:
import { ServiceProvider } from './../../providers/service/service';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, Validators } from '@angular/forms';
import { HomePage } from '../home/home'
import { AlertController } from 'ionic-angular';
import { ToastController } from 'ionic-angular';
@IonicPage()
@Component({
selector: 'page-registro',
templateUrl: 'registro.html',
})
export class Registro {
mensaje : string
registrar : any = {}
constructor(public navCtrl: NavController, public navParams: NavParams, public toastCtrl: ToastController,
public formBuilder : FormBuilder,
public service : ServiceProvider,
public alertCtrl: AlertController) {
this.registrar = this.formBuilder.group({
rut:['', Validators.required],
nombre:['', Validators.required],
apellido:['', Validators.required],
correo:['', Validators.required],
pass:['', Validators.required]});
}
registrarCliente(){
let toast = this.toastCtrl.create({
message : mensaje, //here not work the variable
duration: 3000
});
this.service.registrarCliente(this.registrar.value)
.subscribe(
(data) => {
console.log(data.mensaje);
this.mensaje = data.mensaje;
toast.present();
},
err=>console.log(err)
);
}
}
</div>