【发布时间】:2019-12-29 13:57:32
【问题描述】:
我正在开发一个小型 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}(例如,“石油的未来”)确实显示单个帖子 控制台中的数据。
我的错误在哪里?
【问题讨论】:
标签: angularjs ngroute routeparams