【发布时间】:2017-11-28 15:39:23
【问题描述】:
我正在尝试编写一个简单的 CRUD 操作来在我的 laravel 应用程序中的表中显示帖子列表。我使用服务 $http 将 laravel 与 angular 连接起来。问题是表格中没有显示数据,我只看到空行。
下面我展示了我的 laravel 控制器功能:
public function index(){
$posts = DB::table('posts')->join('categories','posts.category_id','=','categories.id')->
join('users','posts.user_id','=','users.id')
->select('posts.id','posts.topic','categories.category_name','posts.created_at','users.name')->limit(3)->get();
return response()->json($posts,200);
}
web.php 文件中的 Http 请求:
Route::get('api/posts','postsApiController@index');
我的带有 $http 服务的 Angular 控制器代码:
var app = angular.module('app', ['ui.bootstrap','ngSanitize','ngAnimate']).constant('API_URL', 'http://localhost:8000/api/');
app.controller('postsController', function($scope, $http, API_URL) {
$http({
method: 'GET',
url: API_URL + "posts",
}).then(function successCallback(response){
$scope.posts = response;
}, function errorCallback(response){
});
});
在 Google chrome 开发者工具中,在重叠网络中我看到响应:
[{"id":9,"topic":"Odkrycie gwiazdy z ezgoplanet\u0105","category_name":"popularnonaukowe","created_at":"2017-04-16 17:38:59","name":"szarik"},{"id":18,"topic":"Post ze zdj\u0119ciem","category_name":"popularnonaukowe","created_at":"2017-05-07 15:30:52","name":"szarik"},{"id":21,"topic":"Testowy post","category_name":"popularnonaukowe","created_at":"2017-05-26 17:40:07","name":"szarik"}]
这是我的 Blade.php 模板的一部分,我想在其中显示收到的数据:
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Topic</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="post in posts">
<td>@{{ post.topic}}</td>
</tr>
</tbody>
</table>
</div>
我只看到空行:
<tbody>
<!-- ngRepeat: post in posts --><tr ng-repeat="post in posts" class="ng-scope">
<td class="ng-binding"></td>
</tr><!-- end ngRepeat: post in posts --><tr ng-repeat="post in posts" class="ng-scope">
<td class="ng-binding"></td>
</tr><!-- end ngRepeat: post in posts --><tr ng-repeat="post in posts" class="ng-scope">
<td class="ng-binding"></td>
</tr><!-- end ngRepeat: post in posts --><tr ng-repeat="post in posts" class="ng-scope">
<td class="ng-binding"></td>
</tr><!-- end ngRepeat: post in posts --><tr ng-repeat="post in posts" class="ng-scope">
<td class="ng-binding"></td>
</tr><!-- end ngRepeat: post in posts -->
</tbody>
我完全不知道为什么它不起作用。有人可以帮助我如何正确接收这些数据吗?我会非常感激的。 最好的问候
【问题讨论】:
-
把
$scope.posts = response;改成$scope.posts = response.data;并测试一下 -
非常感谢它确实可以正常工作;)
-
欢迎您,如果对您有帮助,请接受我的回答