Maihan Nijat
Maihan Nijat

Reputation: 9355

Get JSON data from PHP using Angularjs 2 Observable

I am trying to get JSON data from PHP using Angularjs 2 Observable. I have PHP file which returns JSON data. I am using Angularjs 2 Observable and have a model (User) but I am getting the following error:

Type 'User' is not assignable to type 'User[]' Property 'length' is missing in type 'User'.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './users.service';
import { User} from './user';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  title = 'کانکور پایلې';

  user: User;


  constructor(private service: UserService) {

  }

  ngOnInit() {
    this.service.getUser().subscribe(user => this.user = user);
  }
}

users.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import { User} from './user';

@Injectable()

export class UserService {

  constructor(private _http:Http) {

  }

  extractData(res: Response){
    return res.json();
  }

  getUser():Observable<User > {
    return this._http
    .get('localhost/data.php')
    .map(this.extractData);
  }
}

user.ts

export class User {
  id: string = '';
  name: string = '';
  fName: string = '';
  lName: string = '';
  gFatherName: string = '';
  school: string = '';
  year: number = 0;
  score: number = 0.00;
  result: string = '';
  province: string = '';
  gender: string = '';

  constructor(values: Object = {}){
    Object.assign(this, values);
  }
}

PHP file

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$dsn = "mysql:host=localhost;dbname=mydb";
$username = "root";
$password = "";

$dbh = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$id = "J01017935";

$output = "";

try {
  $statement = $dbh->prepare("SELECT * from results WHERE id = ?;");
  if($statement->execute(array($id))) {
    while($row = $statement->fetchAll(PDO::FETCH_ASSOC)){
      $output = $row;
    }
  }
} catch(Exception $e){
  print("Error " . $e->getMessage());
  die();
}
$dbh = null;

echo json_encode($output, JSON_UNESCAPED_UNICODE);

?>

Note: I went through almost every question/answer on StackOverflow, watched youtube videos and read other articles but it didn't help. Most of the articles are not straight forward and very complicated for a beginner.

Upvotes: 1

Views: 372

Answers (1)

BeetleJuice
BeetleJuice

Reputation: 40926

The problem is that in Angular, getUser expects the server to return a single User, but it's getting an array that contains a User.

The source of the issue is in how you retrieve info from your DB. Here's your PHP code:

while($row = $statement->fetchAll(PDO::FETCH_ASSOC)){
  $output = $row;
}

fetchAll returns an array of rows. Since only one row is found, $output becomes an array that contains a single element.

The simplest fix is to capture the first (and only) member of fetchAll()

$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$ouput = $results ? $results[0] : null;

You should now be able to json_encode and return $output

Upvotes: 1

Related Questions