【问题标题】:angular 2 service not calling a php fileangular 2 服务不调用 php 文件
【发布时间】:2016-07-23 15:46:42
【问题描述】:

我正在学习 Angular 2,并进行了测试以连接到数据库,但我收到一个错误:SyntaxError: unexpected token

所以我的 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。也许是港口?还是我遗漏的其他东西?

最好的问候

【问题讨论】:

  • 那个 "SyntaxError: unexpected token 可能意味着你的 php 有错误。确保你有一个完全工作的 php 代码。 (你可以使用 chrome 的 POSTMAN 扩展来处理一些花哨的请求)
  • 由于您没有发送任何内容,请从浏览器访问getusers.php。你看到了什么?
  • 我知道。我做的第一件事是检查文件本身,我做了一个 var_dump 并获取数据

标签: javascript php json angular angular2-services


【解决方案1】:

所以由于情况是具有两个端口的跨域。在您的通话中使用带有端口的完整网址: 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);

因为我只是在测试我使用 *,但不建议这样做。通常允许一个特定的 url。

【讨论】:

    【解决方案2】:

    您需要订阅 ajax 调用才能工作; 调用 getUsers 方法的人应该订阅它:

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

    假设你在这里调用 get 方法:

     myOtherFunction(){
         this.getUsers.subscribe((response)=>{
               console.log('response',response);
    
         })
    
    }
    

    【讨论】:

    • 嘿,对不起,我忘了添加这个。在我的组件中,我导入服务,然后导入:`ngOnInit() { this._usersService.getUsers() .subscribe( data => this.getUsers = JSON.stringify(data), error => alert(error), () => console.log("完成") ); }`
    猜你喜欢
    • 2018-05-05
    • 2017-02-03
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2017-02-08
    • 2018-05-26
    • 2017-11-10
    • 2017-08-23
    相关资源
    最近更新 更多