FirebaseExtended / angularfire

AngularJS bindings for Firebase
MIT License
2.73k stars 632 forks source link

Using resolve in controllers #182

Closed dmackerman closed 10 years ago

dmackerman commented 10 years ago

Hey all,

Using the v2 ($firebase) of angularFire. I'm wondering if I can do something similar to this:

.when('/w/:workoutId/e/:exerciseId', {
  templateUrl: 'views/exercise-detail.html',
  controller: 'ExerciseDetailCtrl',
  resolve: {
    exercise: function($firebase, $route) {
      return $firebase(new Firebase("https://***.firebaseio.com/workouts/" + $route.current.params.workoutId + '/exercises/' + $route.current.params.exerciseId));
    }
  }
})

The data doesn't comes back in exercise in my controller. In other words, it doesn't wait to resolve the data before changing the route. I noticed that if I do a $timeout() for several milliseconds, the data is there.

Didn't this use to return a promise? Wondering if this is possible with v2.

kennethlynne commented 10 years ago

This is how I have solved it:

          resolve: {
            exercise: function(dataService) {
              return dataService.get(new Firebase("https://***.firebaseio.com/workouts/" + $route.current.params.workoutId + '/exercises/' + $route.current.params.exerciseId));
            }
          }

Put this in a service

        var factory = function (fbRef, force) {

            var _deferred = $q.defer();

            fbRef.once('value', function (snapshot) {
                if (!force && snapshot.val() == null) {
                    _deferred.reject('Object not found');
                }

                _deferred.resolve( fbRef );
            });

            return _deferred.promise;
        }

Then you're able to handle 404 behavior too by listening for $routeChangeError events

dmackerman commented 10 years ago

Gotcha. That loads the data, but how do I 're-setup' the bindings once I set that to my $scope variable?

kennethlynne commented 10 years ago

Sorry for a misfit example. You just need to do _deffered.resolve ($firebase(fbRef)) instead. I can provide a plnkr if necessary?

dmackerman commented 10 years ago

Ah, beautiful! Thanks.

anantn commented 10 years ago

We moved an example of this into angularFire-seed: https://github.com/firebase/angularFire-seed/blob/master/app/js/module.routeSecurity.js