对象无法从Ionic服务正确返回

时间:2016-05-09 22:10:59

标签: javascript json cordova ionic-framework

背景:我正在制作一个关于纽约地铁的简单离子项目。我正在使用Ionic"标签"模板,我有一个选项卡,列出所有路线及其符号(1,2,3,A,C,E等),用户应该可以点击其中列出的任何路线并采取到一个详细信息页面(有点像他们有一个"聊天/聊天详细信息"当你启动一个新的离子项目时,在标签模板中设置)。

问题是我似乎无法获取路由详细信息页面来加载有关所选路由的信息。 {{route.name}}{{route.desc}}等表达式显示为空白。

routes.json文件(样本,在www/js/routes.json下提交):

{
  "routes": [{
    "id": "1",
    "name": "1",
    "desc": "7 Avenue Local",
    "className": "c123"
  },
  {
    "id": "2",
    "name": "2",
    "desc": "7 Avenue Express",
    "className": "c123"
  },
  {
    "id": "3",
    "name": "3",
    "desc": "7 Avenue Express",
    "className": "c123"
  },
...

app.js:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

// ...

.state("tab.routes", {
  url: "/routes",
  views: {
    "tab-routes": {
      templateUrl: "templates/tab-routes.html",
      controller: "RoutesCtrl"
    }
  }
})
  .state("tab.route-detail", {
    url: "/routes/:id",
    views: {
      "tab-routes": {
        templateUrl: "templates/route-detail.html",
        controller: "RouteDetailCtrl"
      }
    }
  });

controllers.js:

angular.module('starter.controllers', [])

// ...

/* This one works perfectly */
.controller('RoutesCtrl', function($scope, $http) {
  $http.get("js/routes.json").then(function(response) {
    $scope.routes = response.data.routes;

    console.log($scope.routes);
  });
})

/* This one does NOT work */
/* $stateParams.id returns the correct value, but $scope.route
        does not store the Route returned from the service (null) */
.controller("RouteDetailCtrl", function($scope, $stateParams, Routes) {
  $scope.route = Routes.getRoute($stateParams.id);
})

services.js:

angular.module('starter.services', [])

/* This is the problem */
.factory("Routes", function($http) {
  return {
    getRoute: function(id) {
      return $http.get("js/routes.json").then(function(response) {
        var routes = response.data.routes;

        for(var i = 0; i < routes.length; i++) {
          if(parseInt(id) === parseInt(routes[i].id)) {
            return routes[i];
          }
        }

        return null;
      })
    }
  }
})

我认为这个问题与JSON回归services.js的方式有关 - 是我存储JSON的方式,还是我解析&#34;解析&#34的方式;它在接收端? &#34; RoutesCtrl&#34;工作得很好,但无论我在response中使用的services.js变体有什么变化,我似乎无法使路线详细信息正常工作 - 我尝试了response,{{1} },response.data,没有任何作用。

route-detail.html :(正如您所看到的,{{route.whatever}}指的是response.data.routes中的$ scope.route,但它未被存储。)

controllers.js

1 个答案:

答案 0 :(得分:0)

问题不在于routes对象,因为相同的代码在RoutesCtrl中正常工作,但在RouteDetailCtrl中处理响应的方式。从Route服务返回的响应不是原始的javascript值,而是承诺,您需要正确处理承诺才能获得回复:

.controller("RouteDetailCtrl", function($scope, $stateParams, Routes) {
   Routes.getRoute($stateParams.id)
     .then(function (response) {
        $scope.route = response;
     });
})
相关问题