Weston
Weston

Reputation: 1451

ui-router resolve showing previous resolve result on first load, sometimes not showing at all on reloads

So I have it structured like this.

Relevant state code:

       resolve:{
          projectPromise: ['$stateParams', 'projects', 'session', function($stateParams, projects, session){
            projects.getProject($stateParams.id).success(function(data){
              session.currentProject = data;
            });

          }]
        }

getProject:

  o.getProject = function(project_id, container){
   return $http.get('/project/' + project_id);
  };

Inside of the relevant controller:

$scope.currentProject = session.currentProject;

And inside of the relevant template:

{{currentProject.title}}

When I navigate to /projects/:projectid for the first time, it shows the title of the correct project. If I go back and navigate to a new project, however, it still shows the title of the first project. Then when I refresh it shows the correct title. If I keep refreshing after that sometimes the title doesn't appear at all. I'm sure a lot of my problem stems from not having a good understanding of how to structure all of this, like where exactly to call getProject and if getProject should store the result of the $http.get request in a container passed as a parameter or just return like I currently have. Any advice at all is appreciated, thanks!

Upvotes: 0

Views: 63

Answers (1)

Sly_cardinal
Sly_cardinal

Reputation: 13023

You need to return the promise from the resolve function otherwise Angular will navigate to the state before the promise has resolved:

   resolve:{
      projectPromise: ['$stateParams', 'projects', 'session', function($stateParams, projects, session){

        // Add `return` statement here:
        return projects.getProject($stateParams.id).success(function(data){
          session.currentProject = data;
        });

      }]
    }

Upvotes: 3

Related Questions