Angularjs Laravel如何使用angular检索具有用户id的名称?
我只能获取具有title和body属性的数据,但是当我获取名称的数据时,当我刷新页面时,它会显示为空,但当我自动提交时,它会显示为空 由于某些原因,无法成功检索名称 注意:我正在使用 例如: 以下是服务器端: 后置控制器Angularjs Laravel如何使用angular检索具有用户id的名称?,angularjs,laravel,javascript,Angularjs,Laravel,Javascript,我只能获取具有title和body属性的数据,但是当我获取名称的数据时,当我刷新页面时,它会显示为空,但当我自动提交时,它会显示为空 由于某些原因,无法成功检索名称 注意:我正在使用 例如: 以下是服务器端: 后置控制器 public function getPosts() { $posts = Post::with('user')->get(); $response = new Response(json_encode($posts)); $response->hea
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>
作者:
x
首次添加内容而不刷新时(异步)
页面刷新
以上
(不同帖子的不同日志)您的重新加载页面自
$posts = Post::with('user')->get();
返回
{
"title": "title",
"body": "body",
"user": {
"name": "name"
}
}
在你的角度上,你可以通过
<% post.user.name %>
很抱歉,你能进一步解释一下吗?我看到你的问题了,它没有显示在视图上?当然,假设我添加了一篇文章,它会显示文章的用户及其名称,当我刷新页面时,用户名会消失。它只显示标题和正文属性,就像线程中的图像一样。您在图像中看到的第一篇文章是标题和正文内容,没有用户名。您在图像中看到的第二篇文章是标题和正文,有用户名,但是当我刷新名称时disappears@Beginner刷新时不显示名称,仅在我刚刚添加内容时显示(异步)您应该更改
$scope.myposts={}代码>到$scope.myposts=[]代码>。您有:$scope.myposts.push(data.data)代码>$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);
data.data['user'] = {
name: data.data.name
}
$scope.myposts.push(data.data);
});
$scope.post.title = '';
$scope.post.body = '';
};