简体   繁体   English

使用 $routeParams 获取 Angular.js HTTP

[英]Angular.js HTTP Get using $routeParams

I am having a problem trying to get information from a array using Angular.js + PHP.我在尝试使用 Angular.js + PHP 从数组中获取信息时遇到问题。

The idea is: When the user goes to /post/76 (for example), the script will get the ID and return all relevant information (title, content, views, etc).想法是:当用户转到/post/76 (例如)时,脚本将获取ID并返回所有相关信息(标题、内容、视图等)。

$routeProvider $routeProvider

carolvaladares.config(function($routeProvider) {
    $routeProvider.
        when('/post/:postId', {
            templateUrl : 'views/post.html',
            controller  : 'postCtrl'
        })
});

Controller控制器

carolvaladares.controller('postCtrl', function($scope, $http, $routeParams) {

    var postId = $routeParams.postId;

    $http.get("php/get-posts.php?id=" + postId).then(function (response) {
        $scope.post = response.data;
    });

});

PHP PHP

<?php
    require_once("connect.php");
    header('Content-Type: application/json');

    if (isset($_GET['id'])) {
        $id = $_GET['id'];
        $q = mysqli_query($conexao,"SELECT * FROM posts WHERE id = '$id'");
    } else {
        $q = mysqli_query($conexao,"SELECT * FROM posts");
    }

    $result = array();

    while ($get = mysqli_fetch_assoc($q)) {
        $result[] = $get;
    }  

    echo json_encode($result);
?>

(In this case, if the id is specified, it will only get data for one post. Otherwise, it will list data for all posts). (在这种情况下,如果指定了id ,它只会获取一个帖子的数据。否则,它将列出所有帖子的数据)。

There is no problem until now.到目前为止没有问题。 But when I try to print a single field of the array, it returns an empty object [] on console and does not show anything in the HTML.但是当我尝试打印数组的单个字段时,它在控制台上返回一个空对象[]并且在 HTML 中不显示任何内容。

HTML HTML

<div id="post">
    {{post.title}} / DOES NOT WORK /
    {{post}} / WORKS / (PRINTS THE WHOLE ARRAY)
</div>

Thanks in advance.提前致谢。

(EDITED) (已编辑)

Array大批

[
   {
      "id":"76",
      "titulo":"Carrot Cake Americano",
      "sub":"Para esse Fim de Ano, aproveite essa receita maravilhosa de bolo de cenoura!",
      "corpo":"<p>Receitinha mara pra quem vai passar o dia 24 com a barriguinha no fog&atilde;o tipo eu. <strong>o\/<\/strong> Nada mais, nada menos que ele, o tradicional <strong>Carrot Cake Americano.<\/strong><\/p>\r\n<p><strong><img src=\"http:\/\/www.carolvaladares.com.br\/staff\/uploads\/2015\/materia_gastronomia3_carrotcake_cv.jpg\" alt=\"\" \/><\/strong><\/p>\r\n<h2>Bora cozinhar!<\/h2>\r\n<p><strong>Massa &ndash; Ingredientes:<\/strong> <br \/><strong>2<\/strong> x&iacute;caras de farinha de trigo <br \/><strong>1<\/strong> x&iacute;cara de a&ccedil;&uacute;car <br \/><strong>12<\/strong> x&iacute;cara de a&ccedil;&uacute;car mascavo <br \/><strong>2<\/strong> colheres de ch&aacute; de canela em p&oacute; <br \/><strong>1<\/strong> colher de ch&aacute; de noz-moscada <br \/><strong>2<\/strong> colheres de ch&aacute; de bicarbonato de s&oacute;dio <br \/><strong>1<\/strong> colher de ch&aacute; sal <br \/><strong>1\/2<\/strong> x&iacute;cara de passas <br \/><strong>1\/2<\/strong> x&iacute;cara de ovo <br \/><strong>2<\/strong> claras de ovos <br \/><strong>2<\/strong> x&iacute;caras de cenoura ralada <br \/><strong>1\/2<\/strong> x&iacute;cara de ma&ccedil;&atilde; ralada <br \/><strong>1\/3<\/strong> de x&iacute;cara de &oacute;leo <br \/><strong>3<\/strong> colheres de sopa de &aacute;gua quente<\/p>\r\n<p><img src=\"http:\/\/www.carolvaladares.com.br\/staff\/uploads\/2015\/materia_gastronomia_carrotcake_cv.jpg\" alt=\"\" \/><\/p>\r\n<p><strong>Cobertura &ndash; Ingredientes:<\/strong> <br \/><strong>500g<\/strong> de Filadelphia <br \/><strong>1<\/strong> x&iacute;cara de ch&aacute; de a&ccedil;&uacute;car de confeiteiro <br \/><strong>1<\/strong> colher de ch&aacute; de extrato de baunilha <br \/>Nozes para decorar<\/p>\r\n<p><strong>Modo de preparo:<\/strong> <br \/>&mdash; Pr&eacute;-aque&ccedil;a o forno a 250&ordm;C <br \/>&mdash; Pulverize duas bandejas de bolo redondo (9 polegadas) com spray de cozinha sem gordura. <br \/>&mdash; Misture a farinha, os dois tipos de a&ccedil;&uacute;car, canela, noz-moscada, bicarbonato de s&oacute;dio e sal em uma tigela m&eacute;dia. <br \/>&mdash; Bata o ovo e as claras em uma tigela grande. <br \/>&mdash; Adicione a cenoura, ma&ccedil;&atilde;, &oacute;leo e passas e &aacute;gua quente, mexendo at&eacute; misturar. <br \/>&mdash; Com uma esp&aacute;tula, adicione a mistura de farinha &agrave; mistura de cenoura e mexa at&eacute; misturar. <br \/>&mdash; Espalhe a massa uniformemente nas bandejas de bolo. <br \/>&mdash; Asse os bolos at&eacute; dourar cerca de 30-32 minutos.<\/p>\r\n<p>Deixe esfriar por 15 minutos. Retire os bolos da forma e deixe esfriar completamente.<\/p>\r\n<p>Para fazer a cobertura, com a batedeira em velocidade m&eacute;dia-alta, bata os ingredientes da cobertura at&eacute; ficar homog&ecirc;neo. Recheie o bolo e cubra com o creme de cream cheese.<\/p>\r\n<p><img src=\"http:\/\/www.carolvaladares.com.br\/staff\/uploads\/2015\/materia_gastronomia2_carrotcake_cv.jpg\" alt=\"\" \/><\/p>\r\n<p>Doce tem que ser bonito, por isso eu sempre fa&ccedil;o cobertura em bolo com bico de confeiteiro, da&iacute; vai da imagina&ccedil;&atilde;o de cada um. Pique as nozes ou use-as inteiras e jogue por cima.<\/p>\r\n<p>Deixe esfriar e depois se<strong> destrua<\/strong> com o <strong>bolo deuso!<\/strong><\/p>",
      "colunista":"denise",
      "slug":"gastronomia\/carrot-cake-americano",
      "thumbnail":"staff\/uploads\/2015\/denise-materia_gastronomia3_carrotcake_cv.jpg",
      "tags":"carrot cake, cake, carrot, cenoura, bolo, receita, americano, estados unidos, eua, usa, bolo de cenoura",
      "source":"",
      "data":"2015-12-22",
      "hora":"13:00:00",
      "views":"56",
      "categoria":"gastronomia",
      "aprovado":"1"
   }
]

(EDITED) (已编辑)

The solution was {{post[0].x}} and for the HTML content ng-bind-html along with the dependence ngSanitize解决方案是{{post[0].x}}和 HTML 内容ng-bind-html以及依赖ngSanitize

can you show how the printed out array looks?你能展示打印出来的数组的样子吗? Would help in debugging.将有助于调试。

Anyway... My first guess would be that you are missing 1 level of the array when accessing it like无论如何......我的第一个猜测是你在访问它时缺少数组的1级

post[0].title 

Because: mysql_fetch_assoc returns an array and you put that array into an array and encode it with json_encode .因为: mysql_fetch_assoc返回一个数组,您将该数组放入一个数组中并使用json_encode进行编码。

My second guess would be that you have to parse the response first, as its JSON: do我的第二个猜测是你必须首先解析响应,因为它的 JSON: do

$scope.post = JSON.parse(response.data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM