AngularJs报错:Cannot read property 'then' of undefined 求助
Hey there! Let's break down why you're hitting this error and how to fix it.
The Root Cause
The error happens because your dataService.getPessoas() function isn't returning a Promise object. When you try to call .then() on its result, you're actually trying to call a method on undefined, which triggers the error.
How to Fix It
You need to make sure your dataService's getPessoas method returns a valid Promise. Here are the two most common scenarios:
1. If you're using $http for API calls
Your service should explicitly return the Promise from $http (this is the most common mistake—forgetting the return keyword):
angular.module('app') .service('dataService', ['$http', function($http) { this.getPessoas = function() { // Critical: return the $http Promise here return $http.get('/your-api-endpoint/pessoas') .then(function(response) { // Optional: return just the data instead of the full response return response.data; }); }; }]);
2. If you're handling custom async logic
If you're not using $http (e.g., mock data with setTimeout), use AngularJS's $q service to create and return a Promise:
angular.module('app') .service('dataService', ['$q', function($q) { this.getPessoas = function() { var deferred = $q.defer(); // Simulate async work (replace with your actual logic) setTimeout(function() { var mockPessoas = [ { id: 1, nome: "Tatiane" }, { id: 2, nome: "João" } ]; deferred.resolve(mockPessoas); }, 1000); // Critical: return the created Promise return deferred.promise; }; }]);
Bonus: Make Your Controller More Robust
Add a .catch() block to handle errors gracefully once your service is fixed:
function getData() { dataService.getPessoas() .then(function(response) { $scope.pessoas = response; }) .catch(function(error) { console.error('Failed to load pessoas:', error); // Add user-facing error messages here if needed }); };
内容的提问来源于stack exchange,提问作者Tatiane Souto

