2016-05-09 36 views
2

背景:我正在做一个关于纽约地铁的简单离子项目。我正在使用离子“标签”模板,并且我有一个标签,其中列出了所有路线及其符号(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存储方式,还是我在接收端“解析”它的方式? “RoutesCtrl”工作得很好,但我似乎无法获得路线细节工作,无论我在services.js中使用response的哪种变化 - 我尝试过response,response.data,response.data.routes,没有任何工作。

route-detail.html :(如您所见,{{route.whatever}}引用controllers.js中的$ scope.route,但它没有被存储)。

<ion-view view-title="{{route.name}}"> 
    <ion-content class="padding"> 

     <h2>{{route.name}}</h2> 
     <h2>{{route.desc}}</h2> 

     <p>This is the detail page.</p> 

    </ion-content> 
</ion-view> 

回答

0

的问题是不是与路由对象为同一代码在RoutesCtrl但youare处理中RouteDetailCtrl响应的方式工作正常。从Route服务返回的响应是不是一个原始的JavaScript值,而是一个承诺,你需要正确处理的承诺,让您的回应:

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