我正在尝试使用Postgres和Sequelize ORM来调整NodeJs / AngularJs教程http://sahatyalkabov.com/create-a-tv-show-tracker-using-angularjs-nodejs-and-mongodb/。 ORM已经改变,因为它现在使用了Bluebird的承诺。
我正在访问我的数据库以返回一些电视节目,作为回报,我得到一个节目列表和他们的剧集。这是我使用promises之前的HTML:
<div class="col-xs-4 col-md-3" ng-repeat="show in shows | filter:query | orderBy:'rating':true">
<a href="/shows/{{show.id}}"><img class="img-rounded" ng-src="{{show.poster}}" width="100%"></a>
<div class="text-center">
<a href="/shows/{{show.id}}">{{show.name}}</a>
<p class="text-muted">Episodes: {{show.episodes.length}}</p>
</div>
</div>
所以我使用$ resource服务和ng-repeat循环,但是因为我改为承诺我似乎无法访问剧集,但在我的控制台中我看到$ scope.shows是等于 到:
[$promise: Object, $resolved: false]
0: Resource
$$hashKey: 57
Episodes: Array[68]
airs_day_of_week: "Sunday"
airs_time: "9:00 PM"
createdAt: "2014-10-14T10:29:27.287Z"
first_aired: "2008-01-20T00:00:00.000Z"
genre: Array[4]
id: 81189
name: "Breaking Bad"
network: "AMC"
overview: "Walter White, a struggling high school chemistry teacher, is diagnosed with advanced lung cancer. He turns to a life of crime, producing and selling methamphetamine accompanied by a former student, Jesse Pinkman, with the aim of securing his family's financial future before he dies."
poster: "posters/81189-22.jpg"
rating: "9.30"
rating_count: 645
status: "Ended"
updatedAt: "2014-10-14T10:29:27.287Z"
__proto__: Resource
$promise: Object
$resolved: true
length: 1
__proto__: Array[0]
我现在如何访问episodes.length? show.name有效,但show.episodes.length返回undefined。
我的资源调用如下所示:
在控制器中:
$scope.shows = Show.query();
在服务中:
angular.module('MyApp')
.factory('Show', ['$resource',
function ($resource) {
return $resource('/api/shows/:id');
}]);
答案 0 :(得分:1)
值得注意的是,您无法在模板中自由地设置承诺,并希望Angular能够解决这些问题,因为v 1.2:
看看这个SO:
Angularjs promise not binding to template in 1.2
当您从服务中获得结果时,您可以做的是将结果而不是承诺放在范围内:
http://plnkr.co/edit/SU5UMK7jNffXWnWiV1HE?p=preview
SomeService.getSomeData().then(function(res) {
$scope.someData = res;
});
在你的情况下,可能更像是:
ShowsService.getShows().then(function(shows) {
$scope.shows = shows;
});
编辑:当然,既然您使用的是$ resource,而不是Restangular,那么您应该将我的示例转换为$ resource可以接受的内容:
Show.query('', function(shows){
$scope.shows = shows;
});