You're on the right track, but there's one thing missing.
When using the service/factory, it must return a value. Specifically, here:
...
message: function(testservice) {
return testservice.getdata();
}
We expected something to be returned, but nothing was.
I added the line return data;
, and now you can see the updated plunker here.
.factory('testservice', ['$http',
function testservice($http) {
// interface
// implementation
function getData() {
return $http.get("http://jsonplaceholder.typicode.com/photos")
.then(function(data) {
console.log(data)
// This line was missing before
// Make sure to return something here
return data;
}, function(error) {
console.log(error)
})
EXTEND: How to display a loading view before resolution?
I made an extension based on some comments in this example. Now, it shows a loading view:
loadingB.html
<div >
<div ui-view="">
<h2>...loading...</h2>
</div>
</div>
This is a view of a new parent state 'loadingB'
:
.state('loadingB', {
redirectTo: "b",
templateUrl : "loadingB.html",
})
It injects the above view (loadingB.html) into the original state 'b'. It includes a property redirectTo: "b"
, which is managed by this code snippet:
.run(['$rootScope', '$state', function($rootScope, $state) {
$rootScope.$on('$stateChangeSuccess', function(evt, to, params) {
if (to.redirectTo) {
evt.preventDefault();
$state.go(to.redirectTo, params)
}
});
}])
The service now uses $timeout
for a delay:
.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)
...
To redirect to loadingB
, use the following:
$scope.moveto = function() {
$state.go('loadingB');
}
Also, make 'b' a child of 'loadingB':
.state("b", {
parent: "loadingB",
templateUrl: "b.html",
url: "/b",
controller: 'b',
resolve: {
message: function(testservice) {
return testservice.getdata();
},
View all changes here