2016-04-29 113 views
0

我正在测试一个简单的角度应用程序,我正面临一些问题。 http GET调用已完成,但解析器呈现为空。下面是代码:角ui路由器解析http空值

一个简单的index.html:

<html ng-app="myApp"> 
<head> 
    //all scripts loaded 
</head> 
<body ng-controller="myCtrl"> 
    <p>{{test}}</p> 
    <a ui-sref="tab1">Show Tab 1</a> 
    <a ui-sref="tab2">Show Tab 2</a> 
    <a ui-sref="tab3">Show Tab 3</a> 

    <ui-view></ui-view> 
</body> 
</html> 

的app.js:

var app = angular.module('myApp', ['ui.router']); 

app 
.service('DataService', function ($http) { 
    return { 
     getData: function() { 
      return $http({ 
       method : "GET", 
       url : "/hi" 
      }).then(function(response) { 
       return response.data; 
      },function(response) { 
       return "error"; 
      }); 
     } 
    } 
}); 

app 
.controller('myCtrl', function($scope) { 
    $scope.test = "Test"; 
}); 

app 
.config(function($stateProvider, $urlRouterProvider){ 
    $stateProvider 
    .state('tab1', { 
     url: '/tab1', 
     templateUrl: '/assets/templates/tab1.html' 
    }) 
    .state('tab2', { 
     url: '/tab2', 
     templateUrl: '/assets/templates/tab2.html' 
    }) 
    .state('tab3', { 
     url: '/tab3', 
     templateUrl: '/assets/templates/tab3.html' 
     resolve:{ 
      mydata : function (DataService) { 
       return DataService.getData(); 
      } 
     }, 
     controller: 'myCtrl' 
    }); 

    $urlRouterProvider.otherwise('/tab1'); 
}); 

TAB3模板:

<p>Data: {{mydata}}</p> 

正如我所说的,当我单击“tab3”链接,完成http get调用,并检索JSON数据,但“mydata”呈现为空白。

任何线索? 感谢和问候。

+0

尝试打开'Chrome检查 - >网络panel',看看您的Web服务的回报... – Hitmands

回答

1

你的控制器不会对mydata做任何事情。所以它不在范围内,所以视图不能显示它。它应该是:

app.controller('myCtrl', function($scope, mydata) { 
    $scope.mydata = mydata; 
}); 
+0

感谢您的回答,反正我之前试过,但控制器无法找到“MYDATA ”。只是抛出一个错误。我如何注入“mydata”到控制器? – Aroos

+0

这是因为你使用myCtrl作为你的main,index.html页面,尽管它应该是tab3路由的控制器,需要mydata。从index.html中删除'ng-controller =“myCtrl”'。 –

+0

你是对的!非常感谢你!!! – Aroos