我想说,你快到了。
只是服务/工厂必须返回一些东西。我的意思是:
...
message: function(testservice) {
return testservice.getdata();
}
我们期待一些东西......但什么都没有
我加了一行return data;还有that updated plunker
.factory('testservice', ['$http',
function testservice($http) {
// interface
// implementation
function getData() {
return $http.get("http://jsonplaceholder.typicode.com/photos")
.then(function(data) {
console.log(data)
// HERE - this line was missing
// return something here
return data;
}, function(error) {
console.log(error)
})
EXTEND:如何在解析完成之前显示一些视图...正在加载...?
基于我扩展的一些 cmets the example here。它现在显示这个视图:
加载B.html
<div >
<div ui-view="">
<h2>...loading...</h2>
</div>
</div>
这是一个全新父状态的视图'loadingB':
.state('loadingB', {
redirectTo: "b",
templateUrl : "loadingB.html",
})
它将上述视图 loadingB.html 注入到原始状态“b”的位置。它有一个属性redirectTo: "b",由这段小代码管理:
.run(['$rootScope', '$state', function($rootScope, $state) {
$rootScope.$on('$stateChangeSuccess', function(evt, to, params) {
if (to.redirectTo) {
evt.preventDefault();
$state.go(to.redirectTo, params)
}
});
}])
我们的服务现在使用 $timeout 来获得一些延迟:
.factory('testservice', ['$http', '$timeout',
function testservice($http, $timeout) {
// interface
// implementation
function getData() {
return $http.get("http://jsonplaceholder.typicode.com/photos")
.then(function(data) {
console.log("resolved http")
return $timeout(function(){
console.log("after two seconds delay")
return data;
}, 2500)
...
最后,我们必须在这里重定向到loadingB
$scope.moveto = function() {
$state.go('loadingB');
}
并且还让 'laodingB' 的 'b' 孩子
.state("b", {
parent: "loadingB",
templateUrl: "b.html",
url: "/b",
controller: 'b',
resolve: {
message: function(testservice) {
return testservice.getdata();
},
全部查看here