无法使用REST API

时间:2014-09-04 06:22:27

标签: javascript angularjs rest django-rest-framework

我使用Django Rest Framework设置了一个简单的RESTful API,我正在尝试使用AngularJS来使用它。我已经阅读了有关角度的控制器和资源,并且我正在阅读多个教程,但由于某些原因,在我的模板中,我似乎无法正确访问JSON。

app.js

var blogApp = angular.module('blogApp', ['ngResource']);

blogApp.factory('Post', ['$resource', function($resource) {
    return $resource('/api/posts/:slug/', { slug:'@slug'});
}]);

blogApp.controller('postController', ['$scope', 'Post', function($scope, Post) {
    $scope.posts = []

    Post.query().$promise.then(function(posts) {
        $scope.posts = posts;
        for (key in posts){
            console.log(posts[key]);
        }
    });
}]);

的index.html ****编辑****我在这里添加了过滤器以进行测试,它确实按预期进行了过滤,但<div>

仍未显示任何文字
<div class="container">
   <div class="col-sm-10">

      <div ng-controller="postController">
         <input type="text" ng-model="textTest">

         <div class="well" ng-repeat="(key, post) in posts | filter: textTest">
            <h1>{{ post.title }}</h1>
            {{ post.content }}
         </div>
      </div>

   </div>
</div>

如果我在/ api / posts /

上进行GET,这是返回的内容
[
    {
        "url": "http://localhost:8000/api/posts/i-had-a-api-his-name-was-bingo/",
        "id": 0,
        "title": "I had a api... his name was Bingo",
        "content": "E-I-E-I-O",
        "owner": "Heather",
        "comments": "http://localhost:8000/api/posts/i-had-a-api-his-name-was-bingo/comments/"
    },
    {
        "url": "http://localhost:8000/api/posts/if-i-could-show-you-the-world/",
        "id": 1,
        "title": "If I Could Show You The World",
        "content": "It would be shining, and shimmering",
        "owner": "Heather",
        "comments": "http://localhost:8000/api/posts/if-i-could-show-you-the-world/comments/"
    },
    ...
]

在模板中,显示的所有内容都是一个空白的灰色框(因为引导类),帖子中没有标题或内容,但是正确的数量的框确实显示了帖子对象的数量。我错过了什么?

编辑:控制台显示没有错误,GET请求返回200 application / json。我有一个打印出[Resource, Resource, Resource, Resource, Resource, Resource, Resource, $promise: Object, $resolved: true]的console.log($ scope.posts)。此外,

for (key in $scope.posts){
   console.log(posts[key]);
}

打印出来

Resource {url: "http://localhost:8000/api/posts/i-had-a-api-his-name-was-bingo/", id: 0, title: "I had a api... his name was Bingo", content: "E-I-E-I-O", owner: "Heather"…}

3 个答案:

答案 0 :(得分:2)

答案令人沮丧地简单。因为我在我的API中使用了django-rest-framework,而默认情况下django对它的变量使用了双花括号,所以它变得混乱了。我只需要更改分隔符。

var blogApp = angular.module('blogApp', ['ngResource'], function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
     $interpolateProvider.endSymbol(']]');
});

然后在我的模板中使用&#39; [[]]&#39;用于角度变量。 (例如[[ post.title ]]

答案 1 :(得分:0)

你需要放置$ scope。$ apply(),因为这是一个异步调用

答案 2 :(得分:0)

这可能会奏效。

blogApp.controller('postController', ['$scope', 'Post', function($scope, Post) {
    $scope.posts = []

    Post.query().$promise.then(function(posts) {
        $scope.posts = posts;
        $scope.$apply();
    });
}]);