Angular 2服务未调用php文件

罗恩

我正在学习angular 2,并且进行了测试以连接到数据库,但是出现错误:SyntaxError:意外标记<在JSON中的位置0。

所以我让我的xampp在端口80或443上工作。我的测试网址(我正在使用angular cli)是:localhost:4200

这是我的尝试。我用这种方法提供服务:

  getUsers(){
return this._http.get('getusers.php')
  .map(res => res.json());
 }

getusers.php文件位于公用文件夹中。这就是它的内容。非常基本,只是为了获得一些结果并将其作为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;

所以我在导入服务的组件中添加了它,在构造函数中将其初始化并订阅:

  constructor(private _usersService: UsersService) {}

  ngOnInit() {
     this._usersService.getUsers()
       .subscribe(
         data => this.getUsers = JSON.stringify(data),
         error => alert(error),
         () => console.log("Finihed")
      );
  }

我在这里想念什么。我做大量的ajax调用,但是第一次使用angular。也许是港口?还是我想念的其他东西?

此致

罗恩

因此,由于情况是两个端口之间存在跨域。在您的呼叫中,使用带有以下端口的完整URL:http:// localhost:80 / yourproject / public / getContacts.php

并在您的服务器端添加CORS标头,然后输出:

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json');

echo json_encode($result);

因为我只是测试,所以我使用*,但是不建议这样做。通常允许使用特定的网址。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章