2016-11-23 50 views
0

我們正在嘗試更新一個返回承諾的工廠。原始工廠使用$ http-> success->錯誤,並且控制器有一個.then(...)。角落承諾在工廠執行前解決

我們希望從成功/錯誤中「遷移」到/ catch,但是我們在控制器中收到以下錯誤消息:TypeError: Cannot read property 'then' of undefined

工廠方法有以下():

'use strict'; 
xmsbsExtranet.factory('projectsTimeTrackingServices', ['$resource', '$http', '$log', '$q', 'membershipServices', 
    function ($resource, $http, $log, $q, membershipServices) { 
     var serviceBase = 'http://localhost:51617/api/'; 
     var _model = {}; 

     var service = { 
      model: _model, 
      getByProjectId: _getByProjectId_new, 
      upsert: _upsert, 
     }; 
     return service; 

     function _getByProjectId_old(projectId) { 
      var deferred = $q.defer(); 
      $http({ 
       method: "Get", 
       url: "../api/projectsTimeTracking/project/" + projectId 
      }).success(function (response) { 
       deferred.resolve(response); 
      }).error(function (err, status) { 
       //membershipServices.logOut(); 
       deferred.reject(err); 
      }); 

      return deferred.promise; 
     }; 

     function _getByProjectId_new(projectId) { 
      $http.get("../api/projectsTimeTracking/project/" + projectId) 
      .then(function (response) { 
       return response.data; 
      }).catch(function (err, status) { 
       //membershipServices.logOut(); 
       return err; 
      }); 
     }; 

    }]); 

控制器的 「短」 版本被如下:

projectsTimeTrackingServices 
    .getByProjectId(vm.project.xrmId) 
    .then(function (data) { 
     //do something with the data 
    }); 

當服務執行方法 「_getByProjectId_old」,一切按預期工作。但是,如果我將其更改爲「_getByProjectId_new」,則會收到前述錯誤。

任何幫助將不勝感激。 致以問候

回答

3

糾正我,如果我錯了 - 但你實際上並沒有從這個函數的'新'版本返回任何東西。

function _getByProjectId_new(projectId) { 

     //note the new return statement 
     return $http.get("../api/projectsTimeTracking/project/" + projectId) 
    }; 

或代碼(具體取決於您是否想返回 '響應' 或 'response.data'):

function _getByProjectId_new(projectId) { 

     //note the new return statement 
     return $http.get("../api/projectsTimeTracking/project/" + projectId) 
      .then(function (response) { 
       return response.data; 
      }); 
    }; 

function _getByProjectId_new(projectId) { 

     //note that nothing is returned in THIS scope. 

     $http.get("../api/projectsTimeTracking/project/" + projectId) 
     .then(function (response) { 
      return response.data; 
     }).catch(function (err, status) { 
      //membershipServices.logOut(); 
      return err; 
     }); 
    }; 

您可以通過使用此代碼解決這個問題

我不想捕捉這個函數中的錯誤,因爲如果你發現錯誤,你的控制器代碼將無法捕捉到它。

你應該讀一些有關承諾和/ catch鏈的文檔,這有點棘手。

+0

區別在於*'$ http.get'之前的返回語句*。爲了讓控制器能夠調用'.then',必須返回'something'。 – user1935361

+0

你完全正確!非常感謝你的幫助!!! – aplon