首页 > 解决方案 > 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。这让我很困惑,尤其是因为:

  1. console.log(slug);在控制台中显示任何帖子 slug;
  2. {slug}替换为实际的slug (例如“石油的未来”)确实会在控制台中显示单个帖子数据。

我的错误在哪里?

标签: angularjsngrouterouteparams

解决方案


我已经通过替换解决了这个$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>  

有用。


推荐阅读