You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJs报错:Cannot read property 'then' of undefined 求助

Fixing "Cannot read property 'then' of undefined" in Your AngularJS Controller

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:03:26