maria
maria

Reputation: 159

AngularJS post promise

What is acually resolve and postpromise for?

the posts postpromise is to get posts and display them later on. and i want to do the same with sideactions, but how can i make this work?

I have the following code:

    $stateProvider.state('home', {
    url : '/home',
    templateUrl : '/home.html',
    controller : 'MainCtrl',
    resolve : {
            postPromise : ['posts',
        function(posts) {
            return posts.getAll();
        }]
})

but i want to add an additional postpromise.

i tried:

    $stateProvider.state('home', {
    url : '/home',
    templateUrl : '/home.html',
    controller : 'MainCtrl',
    resolve : {

    postPromise : ['posts',
        function(posts) {
            return posts.getAll();
        }],
    postPromise: ['sideactions',
        function(posts) {
            return actions.latestActions();
        }]

    }
})

but that wont work.

How can i make multiple postpromises to the resolve?

Upvotes: 0

Views: 84

Answers (1)

Mikko Viitala
Mikko Viitala

Reputation: 8404

With resolve you can pass data to your controller. Property named postPromise can be replaced with anything you want but there can't be two properties with same name.

Also, in your second postPromise your service names does not match.

Here's an example how to resolve data, using mock services.

HTML

<div>
  <a ui-sref="home">click here for state:home</a>
  <div ui-view></div>
</div>

JavaScript

angular.module('app', ['ui.router'])
  .config(['$stateProvider', function($stateProvider) {
    $stateProvider
      .state('home', {
        url: '/home',
        template: '<div>home template {{ data | json }}</div>',
        controller: function($scope, posts, actions) {
          $scope.data = posts.concat(actions);
        },
        resolve: {
          posts: ['postService', function(postService) {
            return postService.getAll();
          }],
          actions: ['actionService', function(actionService) {
            return actionService.getActions();
          }]
        }
      });
  }])
  .factory('postService', ['$q', function($q) {
    return {
      getAll: function() {
        return $q.when(['post1','post2']);
      }
    };
  }])
  .factory('actionService', ['$q', function($q) {
    return {
      getActions: function() {
        return $q.when(['action1','action2']);
      }
    };
  }]);

image

Related plunker can be found here https://plnkr.co/edit/uOBPQu

Upvotes: 1

Related Questions