我正在尝试使用Angularjs 2 Observable从PHP获取JSON数据。我有PHP文件,它返回JSON数据。我正在使用Angularjs 2 Observable并有一个模型(用户),但我收到以下错误:
键入'用户'不能分配给用户[]'物业长度'是 类型'用户'中缺少。
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文件
<?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);
?>
注意:我在StackOverflow上几乎每个问题/答案,观看了YouTube视频和阅读其他文章,但它没有帮助。对于初学者来说,大多数文章都不是直截了当且非常复杂。
答案 0 :(得分:1)
问题是,在Angular中,getUser
期望服务器返回单个User
,但它会获得包含User
的数组。
问题的根源在于如何从数据库中检索信息。这是您的PHP代码:
while($row = $statement->fetchAll(PDO::FETCH_ASSOC)){
$output = $row;
}
fetchAll
返回一组行。由于只找到一行,$output
成为包含单个元素的数组。
最简单的解决方法是捕获fetchAll()
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$ouput = $results ? $results[0] : null;
您现在应该可以json_encode
并返回$output