Ionic2从php服务器访问api

时间:2016-12-09 11:41:50

标签: angular ionic2

实际上我是 ionic 的新手,但我对 angular2 有一个基本的想法。

我想使用ionic2和angular2访问我在PHP中创建的API。

feed.php

header('Access-Control-Allow-Origin: *');

        $db_name  = 'testdb';
        $hostname = 'localhost';
        $username = 'root';
        $password = '';    

        $dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);

        $sql = 'SELECT * FROM `test_merchants` WHERE 1 LIMIT 1';
        $stmt = $dbh->prepare($sql);
    // execute the query
        $stmt->execute();    

        $result = $stmt->fetchAll( PDO::FETCH_ASSOC );    

        $json = json_encode( $result );
        echo $json;     

home.js

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  posts: any;

  constructor(public http: Http) {
        this.posts = null;
         this.http.get('http://localhost/feed.php').map(res => res.json()).subscribe(data => {
        this.posts = data.id;
        console.log(this.posts);
    });                
  }    
}    

当我点击http://localhost/feed.php时,我得到:

[{"user_id":"136","name":"vikas Merchant","phone_number":"+6512345578","rating":"3","shop_name":"vikas shop","shop_location":"{\"lat\":1.325862,\"lng\":103.892819}","block_number":"11","postal_code":"408723","street":"Ubi Road 1","unit":"#06-48","shop_phone_number":"+651234566","shop_contact_name":"+6598765432","shop_logo":"1470280789-22431.png","shop_description":"testing shop "}]

当我打印控制台日志时,它只显示undefined。我希望控制台日志能够返回类似这些数据:https://www.reddit.com/r/gifs/new/.json?limit=12

1 个答案:

答案 0 :(得分:0)

您必须正确访问json。 你的json是:

[{"user_id":"136","name":"vikas Merchant","phone_number":"+6512345578","rating":"3","shop_name":"vikas shop","shop_location":"{\"lat\":1.325862,\"lng\":103.892819}","block_number":"11","postal_code":"408723","street":"Ubi Road 1","unit":"#06-48","shop_phone_number":"+651234566","shop_contact_name":"+6598765432","shop_logo":"1470280789-22431.png","shop_description":"testing shop "}]

这是一个数组。 您可以将第一个对象作为数据[0]访问。 如果您正在访问user_id,则它将是data [0] .user_id