-1
I have a component calling a service that uses a API in PHP to access a table in a database Mysql and return the information in JSON format.
The HTML presents correctly the table information with `ngFor , but I am not able to use in component routines, because it is like "Undefined".
When I execute a console.log(this.objetivos)
, is indicating "Undefined" and the Angular does not allow me to iterate.
When I tried to do JSON.parse
, message appears
Syntaxerror: Unexpected token u in JSON at position 0
Component:
import { Component, OnInit } from '@angular/core';
import { ObjetivosService } from './objetivos.service';
@Component({
selector: 'app-objetivos',
templateUrl: './objetivos.component.html',
styleUrls: ['./objetivos.component.css']
})
export class ObjetivosComponent implements OnInit {
objetivos;
objetivosJ;
constructor(private objetivosService: ObjetivosService) { }
ngOnInit() {
this.getObjetivos();
}
getObjetivos() {
this.objetivosService.getObjetivos().subscribe(objetivos => { this.objetivos = objetivos });
console.log(this.objetivos);
this.objetivosJ = JSON.parse(this.objetivos);
console.log(this.objetivosJ);
}
}
Service:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Injectable()
export class ObjetivosService {
//private data;
//getData: string;
constructor(private http: HttpClient) { }
getObjetivos() {
return this.http.get("API/objetivos.php");
}
}
HTML:
<h2>
Meus Objetivos
</h2>
<div class="collection">
<a href="#!" class="collection-item"
*ngFor="let objetivo of objetivos"
[routerLink]="['/objetivo', objetivo.idobjetivo]">
ID-Objetivo {{ objetivo.idobjetivo }} Data {{ objetivo.dataobjetivo }} Objetivo {{ objetivo.objetivo }}
</a>
</div>
Now the following error is occurring: ERROR Syntaxerror: Unexpected token o in JSON at position 1 at JSON.parse (<Anonymous>) at Safesubscriber. _next (objectives.component.ts:38) ...
– Luiz Bordoni
It seems that the json that your PHP comes back is invalid. Check that the content of the reply is a valid json
– Kaoe Coito
I believe that the JSON returned by PHP is valid because HTML can present the information correctly in the Browser. 

Resposta do PHP:

[{"idobjetivo":"15","idatleta":"83","dataobjetivo":"2018-07-29","objetivo":"Treino base","tpreg":"A"},{"idobjetivo":"21","idatleta":"83","dataobjetivo":"2018-06-10","objetivo":"Treino H2","tpreg":"A"}]
– Luiz Bordoni