【问题标题】:AngularJS fetching single post by slug with $routeParams failsAngularJS 使用 $routeParams 通过 slug 获取单个帖子失败
【发布时间】: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。这让我很困惑,尤其是因为:

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

我的错误在哪里?

【问题讨论】:

    标签: angularjs ngroute routeparams


    【解决方案1】:

    我已经通过将$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>  
    

    有效。

    【讨论】:

    • 与之前版本的重要区别是您必须在使用它之前定义slug 变量。回调函数在服务器响应之后执行。
    • @Scorpioo590 实际上,const slug = $routeParams.slug; $http.get('api/{slug}').then(function(response) { $scope.post = response.data.post; }); 不起作用。
    • 是的,当然,因为{slug} 只是字符串的一部分,而不是变量的占位符。我只是想强调一下,回调函数是在发出请求后执行的。
    【解决方案2】:

    试试 'api/:slug'。而不是 http get 中的 {slug}

    【讨论】:

    • 我找到了可行的解决方案。如果有兴趣,请查看 here
    猜你喜欢
    • 2015-02-01
    • 2013-02-05
    • 1970-01-01
    • 2014-02-08
    • 2018-01-22
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    相关资源
    最近更新 更多