How to get a string from a json?

Asked

Viewed 62 times

0

I am developing an application and need to save in a variable of string type what comes in the server json. How to solve?

 export class InicioPage {
  
  users : any[];
  vaga  : any[];
  nomes : boolean = true;  
  elementType : 'url' | 'canvas' | 'img' = 'url';
  value; //= 'Código gerado';  
  constructor(public navCtrl: NavController,
              private alertCtrl: AlertController,
              public service : ServiceProviderInicio,
              //public service1 : ServiceProvider
              

            ) {
    this.value = {};
  }

  ngOnInit() {
           this.getVaga();
           this.getDados();
     }

  /*  getDados() {
     //retorno de Dados
     this.service.getData()
           .subscribe(
                 data=> this.users = data
                 ,err=> console.log(err)
           );
     }*/

     getDados() {
     //retorno de Dados
     this.service.getData()
           .subscribe(
                 data=> this.users = data
                 ,err=> console.log(err)
           );
     }
}

excerpt performs a request in the database

@Injectable()
export class ServiceProviderInicio {

      api : string = 'http://localhost:80/APIEST/inicio/';


  constructor(public http: Http) {}
      getData() {
            return this.http.get(this.api + 'apiRecuperaInicio.php').map(res=>res.json())
      }
}

and server query

<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html; charset=utf-8');
//recupera login usuario

$dns = "mysql:host=localhost;dbname=estacionamentobd";
$user = "root";
$pass = "";
//aqui

try {
	$con = new PDO($dns, $user, $pass);

	if(!$con){
		echo "Não foi possivel conectar com Banco de Dados!";
	}

	$query = $con->prepare("SELECT * FROM usuario");

		$query->execute();

		$out = "[";

		while($result = $query->fetch()){
			if ($out != "[") {
				$out .= ",";
			}
			$out .= '{"id_usuario": "'.$result["id_usuario"].'",';
			$out .= '"login": "'.$result["login"].'"}';
		}
		$out .= "]";
		echo $out;




} catch (Exception $e) {
	echo "Erro: ". $e->getMessage();
};

need to save in the value variable as string type. Thank you

  • In which part of the code is the request being made ? Could you put the request code in the question ? 'Cause I see you’re calling the shot getDados() but I don’t see it in the code.

  • I updated the post as requested Wellingthon. Thank you

1 answer

2

What you can do is getData().subscribe(res => this.value = JSON.stringify(res)). If that’s what I understood, it would be :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.