2015-02-11 128 views
2

下面是我的控制器代碼:函數返回undefined AngularJS

/////// 
//Diary Notes Controller 
/////// 
diary.controller('NotesController', ['$scope','$http', 'notesService', function ($scope, $http, notesService){ 

// 
//Get the Notes data back from the Server 
// 

$scope.updateFunc = function() { 

    var notes = notesService.getText(); 

    console.log(notes); 

}; 

$scope.updateFunc(); 

我的服務代碼:

diary.factory('notesService', function ($http) { 

return { 

    getText: function() { 

     $http.get('www/getNotes.php') 
      .then(
      function (payload){ 
       return payload.data; 
      }); 

    } 

} 

}); 

基本上當我做CONSOLE.LOG未定義的notes變量似乎尷尬控制器返回因爲當我使用控制器來獲取有效負載時,但從服務中返回有效負載似乎不起作用。

回答

2

$http.get是異步函數,返回HttpPromise。有幾種方法,你如何能得到data

1.Pass callback,這樣

diary.factory('notesService', function($http) { 
    return { 
    getText: function (callback) { 
     $http.get('www/getNotes.php') 
     .then(
     function(payload) { 
      callback(payload.data); 
     }); 

    } 
    } 
}); 


notesService.getText(function (notes) { 
    console.log(notes); 
}); 

2.return promise

diary.factory('notesService', function($http) { 
    return { 
    getText: function() { 
     return $http.get('www/getNotes.php'); 
    } 
    } 
}); 

notesService.getText().then(
    function(payload) { 
     callback(payload.data); 
    }); 
1

你得到undefined,因爲你沒有從getText()返回任何東西。在方法的$http調用之前添加return語句:

getText: function() { 
    return $http.get('www/getNotes.php') 
     .then(
     function (payload){ 
      return payload.data; 
    }); 
} 

隨後致電承諾then方法來獲取值:

notesService.getText().then(function(notes) { 
    console.log(notes); 
}); 
+0

感謝您的答覆。返回是我需要的工作。現在它在Controller中返回承諾值.. :)謝謝 – ChanX 2015-02-11 09:21:47

1

$http.get返回Promise

由於then中的承諾回調是異步的,因此您需要處理控制器中的承諾。要做到這一點,首先返回承諾在工廠:

return $http.get('www/getNotes.php') <-- return added at the beginning of this line 
.then(function (payload){ 
    return payload.data; 
}); 

,然後辦理承諾在控制器:

$scope.updateFunc = function() { 
    notesService.getText().then(function(notes) {  
     console.log(notes); 
    });; 
}; 
+0

可以承諾在工廠而不是控制器處理? – ChanX 2015-02-11 09:26:35

+0

*你處理*是什麼意思?它是異步的。 – 2015-02-11 10:23:06

+0

我的意思是如果我可以處理返回值並將其添加到數組.etc – ChanX 2015-02-11 12:33:33

1

的問題是,你沒有返回上的getText函數的任何信息。如果您從$ http.get返回承諾,則應執行任何承諾方法以實現您的模型變量備註

diary.factory('notesService', function ($http) { 

    return { 

     getText: function() { 

      return $http.get('www/getNotes.php') 
       .then(
       function (payload){ 
        return payload.data; 
       }); 

      } 

      } 
    });