【发布时间】:2018-04-28 03:31:24
【问题描述】:
我只能获取具有标题和正文属性的数据,但是当我获取名称的数据时,它在我刷新页面时显示为空,但在我自动提交时显示。
由于某种原因,angularjs 未成功检索名称。
注意:我使用的是laravel。
例如这里:
这里是服务器端:
后控制器
public function getPosts() {
$posts = Post::with('user')->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function storePost(Request $request) {
$data = request()->validate([
'title' => 'required|max:120',
'body' => 'required|max:1000'
]);
$data['user_id'] = auth()->user()->id;
$data['name'] = auth()->user()->name;
$post = Post::create($data);
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
// return redirect('/home')->withMessage('A new post was created.');
return $response;
}
main.js
$scope.myposts = {};
$scope.addPost = function() {
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
console.log(data);
$scope.myposts.push(data.data);
});
$scope.post.title = '';
$scope.post.body = '';
};
$scope.deletePost = function(post) {
var index = $scope.myposts.indexOf(post);
if (index != -1) {
$scope.myposts.splice(index, 1);
}
$http.delete('auth/post/' + post.id);
};
$scope.getPosts = function() {
$http.get('/auth/posts').then(function(data) {
$scope.myposts = data.data;
}).then(function(data, status, header, config) {});
};
HTML:
<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
<div id="eli-style-heading" class="panel-heading">
<% post.title %>
</div>
<div class="panel-body panel">
<figure>
<p>
<% post.body %>
</p>
by:
<p>
<% post.user.name %>
</p>
</figure>
<span><button ng-click="deletePost(post)">x</button></span>
</div>
</div>
当我第一次添加内容而不刷新时(异步)
页面刷新
以上 (不同帖子的不同日志)
【问题讨论】:
-
很抱歉,您能进一步解释一下吗
-
啊我看到你的问题它没有显示在视图中?
-
当然,假设我添加了一个帖子,它显示帖子用户及其名称,当我刷新页面时,用户的名称消失了。它只显示标题和正文属性,如线程中的图像。您在图像中看到的第一个帖子是标题和正文内容,没有用户名您在图像中看到的第二个帖子是标题和正文,有用户名,但是当我刷新时,名称消失了
-
@Beginner 刷新时不显示名称,仅在我添加内容(异步)时才显示
-
您应该将
$scope.myposts = {};更改为$scope.myposts = [];。你有:$scope.myposts.push(data.data);。$scope.myposts必须是数组[]。
标签: angularjs laravel javascript angularjs laravel