angularjs - AngularJS 使用 $routeParams 通过 slug 获取单个帖子失败
问题描述
我正在开发一个小型 AngularJS 博客应用程序(我使用的框架版本是 1.7.8)。
我已经设法从我自己制作的 API 中提取和显示帖子。
我在显示单个帖子时遇到问题,我无法找出其原因。
我的 app.js 文件:
angular.module('app', [
'ngRoute',
'app.controllers',
'ngSanitize'
]).config(['$routeProvider', function($routeProvider){
$routeProvider.when('/', {
templateUrl: 'templates/posts.html',
controller: 'PostsController'
}).when('/:slug', {
templateUrl: 'templates/singlepost.html',
controller: 'SinglePostController'
}).when('/page/:id', {
templateUrl: 'templates/page.html',
controller: 'PageController'
}).otherwise({
redirectTo: '/'
});
}]);
在我的两个控制器中,只有第一个可以按需要工作:
// All posts
.controller('PostsController', ['$scope', '$http', function($scope, $http){
$http.get('api').then(function(response) {
//Categories
$scope.categories = response.data.categories;
// Posts
$scope.posts = response.data.posts;
// Pages
$scope.pages = response.data.pages;
});
}])
// Single post
.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
$http.get('api/{slug}').then(function(response) {
const slug = $routeParams.slug;
console.log(slug); //consoles the slug post
console.log(response.data.post); //consoles null
});
}])
控制台中的SinglePostController
显示post: null
。这让我很困惑,尤其是因为:
console.log(slug);
在控制台中显示任何帖子 slug;{slug}
替换为实际的slug (例如“石油的未来”)确实会在控制台中显示单个帖子数据。
我的错误在哪里?
解决方案
我已经通过替换解决了这个$http.get('api/{slug}')
问题$http.get('api/' + slug)
。
现在,在控制器中我有:
// Single post
.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
const slug = $routeParams.slug;
$http.get('api/' + slug).then(function(response) {
//Send single post to the view
$scope.post = response.data.post;
});
}])
在我看来:
<div class="content">
<h1>{{post.title}}</h1>
<div class="meta">Published on {{{post.created_at}} by {{post.first_name}} {{post.last_name}}</div>
<div class="post-content">{{post.content}}</div>
</div>
有用。
推荐阅读
- docker - Azerothcore 通过 Docker 连接到互联网
- excel - 编辑条件格式公式
- c - 我应该如何解释 gstreamer multifilesink 时间戳属性?
- angular - 角度 bitbucket heroku 部署后超出内存配额
- c# - 在 Microsoft Bot Framework 的 sdk v4 中使用 FormDialog
- r - 闪亮的去抖不会呈现初始情节
- c# - 期望 blob 时向浏览器返回有意义的错误字符串
- apache-flink - 读取文本文件 flink
- javascript - 如何使用 Nest.js 在开发中提供 MockService?
- html - 使用 html / ejs 在页面标题旁边有一个图标