从动态URL检索数据-角度 [英] Retrieving data from dynamic URL - angular

查看:66
本文介绍了从动态URL检索数据-角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码检索数据,其中服务的URL具有动态参数,即. id ,这是错误的,因为当我在浏览器中加载URL时,数据没有显示,最后是这样:

I'm trying to retrieve data with the following code, where the URL of the service has a dynamic parameter ie. the id, there is something wrong because the data isn't displaying, when I load the URL in the browser with this on the end:

../categories/165

请给我一些帮助吗?谢谢.

could I get some help please? Thanks.

   ...  
    .when('/categories/:categoryId', {
        controller: 'BookCategoryController',
        templateUrl: 'views/booksincategory.html'
    })
    ...

控制器

app.controller('BookCategoryController', ['$scope', 'bookcategories', '$routeParams',  function($scope, bookcategories, $routeParams) {
    bookcategories($scope.id).success(function(data) {
     console.log($scope.id);
    $scope.detail = data.books[$routeParams.categoryId];
    });
}]);

服务

  app.service('bookcategories', ['$http', function($http) {
      return {
        get: function(id) {
          return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
            .success(function(data) {
              return data;
            })
            .error(function(err) {
              return err;
            });
        }
      }
    }]);

booksincategory.html

  <div class="category col" ng-repeat="book in detail">
     <h3 class="title">{{book.title}}</h3>
  </div>

推荐答案

将您的服务代码更改为:

Change your service code to :

 app.service('bookcategories', ['$http', function($http) {
      return {
        getAllBooks: function(id) {
          return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
         }
      }
}]);

并在Controller中:

and in Controller :

 bookcategories.getAllBooks($scope.id).then(function(response) {
    $scope.detail = response.data.books[$routeParams.categoryId];
 });

EDIT2

您必须在控制器中的某个位置定义 $ scope.id ,如下所示:

You have to define $scope.id somewhere in your controller like below :

$scope.id= 1 ; 
console.log($routeParams.categoryId);//check what you are getting here
bookcategories.getAllBooks($routeParams.categoryId).then(function(response) {
   $scope.detail = response.data.books[$routeParams.categoryId];
});

此后,您的服务URL将如下所示(从您的问题中获取此URL) http://52.41.65.211:8028/api/v1/categories/1/books.json

after this your service URL will go like below (Took this URL from your Question) http://52.41.65.211:8028/api/v1/categories/1/books.json

在URL中查看 1 ,其 $ scope.id

这篇关于从动态URL检索数据-角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆