简体   繁体   English

如何访问参数以获得$ resource中的单个对象?

[英]How to access params to get a single object in $resource?

So I am trying to get a single "post" object from a list of posts but i don't know the name of passed params object name. 因此,我试图从帖子列表中获取单个“ post”对象,但我不知道传递的params对象名称的名称。 Here's post-details component 'use strict'; 这是细节后的组件“严格使用”;

angular.module('postDetail', ['ngRoute', 'postsService'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/posts/:postId', {
    templateUrl: 'post-detail/post-detail.template.html',
    controller: 'PostDetailController'
  });
}])

.controller('PostDetailController', ['$scope', '$http', 'postsService', '$routeParams', function($scope, $http, postsService, $routeParams) {
    $scope.post = postsService.getPost($routeParams.postId);
}]);

Here I am passing postId to the getPost method. 在这里,我将postId传递给getPost方法。 BTW, here the value of postId is valid. 顺便说一句,这里的postId的值是有效的。

This is my Posts Service. 这是我的邮政服务。

angular.
  module('postsService', ['ngResource']).
  factory('postsService', ['$resource',
    function($resource) {
      return $resource('https://jsonplaceholder.typicode.com/posts/:postId', {}, {
        getPost: {
          method: 'GET',
          params: {postId: '@postId'}
        }
      });
    }
  ]);

But here the "@postId" expression is empty and it tries to get the list of posts. 但是这里的“ @postId”表达式为空,它试图获取帖子列表。 How can i reference the passed parameter? 如何引用传递的参数?

My post details template 我的帖子详细信息模板

<h3>{{post.title}}</h3>
<p>{{post.body}}</p>

Instead of: 代替:

$scope.post = postsService.getPost($routeParams.postId);

do: 做:

$scope.post = postsService.getPost({
    postId: $routeParams.postId
});

Check out the example of how to use $resource class methods in the documentation . 文档中查看如何使用$resource类方法的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM