简体   繁体   中英

AngularJs : Restangular

I have just discovered the Angular "Restangular" library, and oh my it does look great! However, I am running into complications when performing some simple GET requests with it. I am just experimenting and attempting to return a list of JSON objects from one of my API routes. The GET request to the server is being made successfully, however when I attempt to bind the results to the $scope object and display them, I cannot seem to get it working. Please refer to my controller script where I initialise and use the getList() method to retrieve the list of objects.

angular.module("app")
    .controller("BlogsController", function ($scope, $location, Restangular) {
    var Blogs = Restangular.all("blogs");
    $scope.list = function () {
        $scope.blogs = Blogs.getList("blogs");
    }

I have bind initialised the "list()" function on the HTML page, and am using the ng-repeat directive to loop through all the JSON objects. This is my HTML markup below:

<tr data-ng-repeat="blog in blogs">
    <td>{{blog.title}}</td>
    <td>{{blog.category}}</td>
    <td>{{blog.author}}</td>
    <td>{{blog.content}}</td>
    <td>{{blog.createdOn}}</td>
</tr>

I am very new to the AngularJs framework, and would like to know if anyone knows the potential problem that I am being faced with. Please comment and let me know what needs to be fixed. All answers will be greatly appreciated, Thanks.

You have to use the $object property of the promise which getList() returns. This is where the values from the HTTP response will be filled in when the promise is resolved.

$scope.blogs = Blogs.getList("blogs").$object;

Another, more explicit and less "magical" way of fetching the values is to attach callbacks to the promise returned by getList() , which will be called when the promise is resolved:

Blogs.getList("blogs").then(function(blogs) {
    // Success callback
    $scope.blogs = blogs;
}, function(error) {
    // Error callback
    console.log("we had an error here ...");
});
var Blogs = Restangular.all("blogs").getList();

this is your promise, you have to resolve it with then() like this

Blogs.then(function(blogs){
   $scope.blogs = blogs;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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