我在Angular2框架中是全新的,我遇到了http get请求的问题。我想在我的主页上显示所有注册用户。
这是我的代码:
home.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class UserService {
constructor (
private http: Http
) {}
getUser() {
return this.http.get(`/app/home/home.php`)
.map((res:Response) => res.json());
}
}
home.component.ts:
// Imports
import { Component, OnInit } from '@angular/core';
import { UserService } from './home.service';
@Component({
templateUrl: './home.component.html'
})
// Component class implementing OnInit
export class HomeComponent{
// Private property for binding
constructor(private userService: UserService) {}
profile = {};
loadUser() {
this.userService.getUser().subscribe(data => this.profile = data);
}
}
home.php
<?php
$connection = new mysqli("127.0.0.1", "root", "", "flatmate");
if($connection->connect_error){
echo $connection->connect_error;
}
/* change character set to utf8 */
if (!$connection->set_charset("utf8")) {
echo $connection->error;
exit();
}
$getUser = 'SELECT * from users';
$result = mysqli_query($connection, $getUser);
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
echo json_encode($data);
home.component.html:
<div>
<button (click)="loadUser()">Load profile</button>
{{ profile | json }}
</div>
在我的app.module.ts
我添加了UserService
提供商。我根据this tutorial准备了我的代码。当我从此示例传入get方法URL时,代码正常工作。但如果我改变链接到我的home.php我得到错误:
“errors.ts:42 ERROR SyntaxError:意外的标记&lt;在位置0的JSON中”