spacek33z
spacek33z

Reputation: 2253

Return value of a promise to a function in AngularJS

I have a problem with outputting the values of a promise function.

$scope.getTeacher = function(teacherAbr) {
  var promise = dataService.getTeacher(teacherAbr);

  var testje = promise.then(function(payload) {
    return payload;
  });

  return testje; // outputs an d object, not the direct payload values
};

The output of this controller function is this: output of function

However, when I'm doing testje.$$state it returns undefined. How can I output the value object? I can't output the payload variable in a new $scope, because this data is dynamic.

Here is a simplified version of this on Plunker.

Upvotes: 2

Views: 4920

Answers (2)

dfsq
dfsq

Reputation: 193301

You should change the way you think about things when you work with asynchronous code. You no longer return values, instead you use Promise or callback patterns to invoke code when data becomes available.

In your case your factory can be:

.factory('dataService', function($http, $log, $q) {
    return {
        getTeacher: function(teacher) {
            // Originally this was a jsonp request ('/teacher/' + teacher)
            return $http.get('http://echo.jsontest.com/key/value/one/two').then(function(response) {
                return response.data;
            }, function() {
                $log.error(msg, code);
            })
        }
    };
});

And usage in controller:

dataService.getTeacher('Lanc').then(function(data) {
    $scope.teacher = data;
});

Also $http.get already returns promise, so you don't have to create one more with $q.defer().

Demo: http://plnkr.co/edit/FNYmZg9NJR7GpjgKkWd6?p=preview

UPD

Here is another effort for combining lessons with teachers.

Demo: http://plnkr.co/edit/SXT5QaiZuiQGZe2Z6pb4?p=preview

Upvotes: 6

shamon shamsudeen
shamon shamsudeen

Reputation: 5858

//in your services file

  return {
      getTeacher: function (teacher) {
        // Originally this was a jsonp request ('/teacher/' + teacher)
       return $http.get('http://echo.jsontest.com/key/value/one/two')

        })

//change the controller to this

dataService.getTeacher(teacherAbr).then(function(msg){

     $scope.getdata=msg.data;
      console.log("From server"+msg.data);

});

Upvotes: 0

Related Questions