El Hombre Sin Nombre El Hombre Sin Nombre - 1 month ago 10
AngularJS Question

Get an element by id with Angular service

I have a

service
to get (with array) all post from a server. I need to filter this array by id and show only this post in a single page.

In the service I have this code.

.service('PostAPI', function($http) {
this.getAll = function() {
return $http.get("ajax/getAllPosts.php");
}
this.getOne = function(data) {
return $http.get("ajax/searchPost.php?postID=" + data);
}
this.delete = function(data) {
if (confirm("Are you sure to delete this line?")) {
return $http.delete("ajax/deletePost.php?postID=" + data);
}
}
this.update = function(data) {
return $http.put("ajax/updatePost.php?postID" + data);
}
this.create = function() {
return $http.post("ajax/addPost.php");
}
})


In the controller

.controller("PostControlador", function($scope, $routeParams, PostAPI) {
GetPost();
$scope.title = "Editar post";

function GetPost() {
PostAPI.getOne($routeParams.id).success(function(data) {
$scope.post = data;
console.log($scope.post);

});
};


In post HTML I have this.

<div>
<div>{{post.TASK}}</div>
<div>{{post.STATUS}}</div>
<a href="#/posts/"><b>Back</b></a>
</div>


I'm not able to get any data to show in the page, and also, i have no errors in my console. ┬┐Any idea?

Answer

Check your ajax/searchPost.php?postID= api that is this api returning single object or array, If this api returning object than it should work but If you getting array of single element in response of api then in your api success code use first element of array by data[0].

Controller code

.controller("PostControlador", function($scope, $routeParams, PostAPI) {
    GetPost();
    $scope.title = "Editar post";

    function GetPost() {
        PostAPI.getOne($routeParams.id).success(function(data) {
            $scope.post = data[0];
            console.log($scope.post);

        });
    };
Comments