tkuichooseyou
tkuichooseyou

Reputation: 650

Angular: using promise in service to store data once, cache

I'm trying to use a service to store the data from my API, and only make a call to the API once across different pages. Right now I have a solution working with the controller accessing the service's promise and setting the scope variable in the callback, but I was wondering if there was a way to make this cleaner. I saw in another thread that $http.get returns a promise so there should be a way to make use of that, but when I tried using the answer from yohairosen in the following question, but it didn't set my variable properly:Use Promise and service together in Angular

Here's my code

/app/scripts/services/team.js

app.factory('Team', function($http, $q) {
  var deferred = $q.defer();

  $http.get('/api/teams').success(function(teams){
    deferred.resolve(teams);
  });

  return {
    promise: deferred.promise,
  }
});

/app/scripts/controllers/teams.js

app.controller('TeamsCtrl', function ($scope, $routeParams, Team) {
  Team.promise.then(function(data){
    $scope.teams = data;
  });
});

Upvotes: 1

Views: 1656

Answers (1)

Bob Fanger
Bob Fanger

Reputation: 29897

With promises you can chain then calls.

app.factory('Team', function($http) {

  return {
    promise: $http.get('/api/teams').then(function (response) {
      return response.data;
    })
  }
});

This notation is not only shorter, but failures($q.reject) are also propagated.

Upvotes: 3

Related Questions