i'm learning angular 2 and i make a test to connect to a database, but i get an error that: SyntaxError: unexpected token < in JSON at position 0.
so i have my xampp working on port 80 or 443. the url of my test ( i'm using angular cli ) is: localhost:4200
this is my attempt. i have a service with this method:
getUsers(){
return this._http.get('getusers.php')
.map(res => res.json());
}
the getusers.php file is located at the public folder. this is it's content. very basic just to get some results and send them back as json:
// set up the connection variables
$db_name = 'mydb';
$hostname = 'localhost';
$username = 'myusername';
$password = 'mypass';
// connect to the database
$dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);
$sql = 'SELECT * FROM users';
$stmt = $dbh->prepare( $sql );
$stmt->execute();
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
$json = json_encode( $result );
echo $json;
so i add that in the component i import the service, initialize it in the constructor and subscribe:
constructor(private _usersService: UsersService) {}
ngOnInit() {
this._usersService.getUsers()
.subscribe(
data => this.getUsers = JSON.stringify(data),
error => alert(error),
() => console.log("Finihed")
);
}
what am i missing here. i do tons of ajax call but first time with angular. maybe it's the ports? or something else i am missing?
best regards
getusers.phpfrom the browser. What do you see?