【问题标题】:Ionic2 accessing api's from php serverIonic2 从 php 服务器访问 api
【发布时间】:2016-12-12 20:50:18
【问题描述】:

实际上,我对 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

【问题讨论】:

    标签: angular ionic2


    【解决方案1】:

    您必须正确访问 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 "}]
    

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

    【讨论】:

    • 非常感谢@Suraj 对我来说就像一个魅力。你能帮我分享一些参考资料吗
    • 我现在没有任何链接 :) 这是经验。以后发现会更新
    • 嗨,Suraj,您能帮我弄清楚如何在我到达这里时执行后期操作。提前致谢。
    • 最好在 StackOverflow 中提出一个新的精确问题
    • 肯定是苏拉杰。
    猜你喜欢
    • 2017-08-04
    • 2014-11-14
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多