簡體   English   中英

在返回promise的函數上使用.success時,Undefined不是函數

[英]Undefined is not a function when using .success on a function that returns a promise

我試圖通過編寫登錄功能來繼續我對諾言的理解。 Login函數是AuthService的一部分,該AuthService向我的服務器發送一個http請求並返回一個Promise(如果已驗證用戶,則Promise被解決,否則被拒絕)。

在控制器中調用該函數時,由於該函數返回一個Promise,但我嘗試使用.success和.error,但出現錯誤“ Undefined is not a function”。

這是我的函數,得到未定義的錯誤。

$scope.login = function(email, password) {
  return AuthService.login(email, password).success(function(data) {
    return console.log("login function returned", data);
  }).error((function(data) {
    return console.log("There was an error " + data);
  }));
};

這是我的服務

.service('AuthService', function($window, $rootScope, $q, $http) {
  return {
    login: function(email, password) {
      var deferred;
      deferred = $q.defer();
      $http.post('/dashboard/login', {
        email: email,
        password: password
      }).error(function(error, status) {
        console.log("Incorrect logi");
        return deferred.reject(error);
      }).success(function(data, status) {
        $window.sessionStorage["userInfo"] = JSON.stringify(data);
        return deferred.resolve(data);
      });
      return deferred.promise;
    }
  };
});

最讓我困惑的是,經過研究,promise似乎沒有成功或錯誤的方法,但是$ http是具有該方法的promise。 另外,如果他們沒有成功和錯誤,您怎么知道某事是否是錯誤? 最后,如果沒有成功或錯誤方法,.reject和.resolve有什么意義?

最讓我困惑的是,經過研究,promise似乎沒有成功或錯誤的方法,但是$ http是具有該方法的promise

確實是的。 $http返回對象是基於傳統原因具有這些.success.error方法的.success

如果他們沒有成功和錯誤,您怎么知道某事是否是錯誤?

將處理程序附加到.then()的標准方法是使用.then()方法 ,該方法還用作鏈接方法,並為處理程序的結果返回一個新的Promise。

因此代碼看起來像這樣(也避免了延遲的反模式 ):

.service('AuthService', function($window, $rootScope, $q, $http) {
  return {
    login: function(email, password) {
      return $http.post('/dashboard/login', {
        email: email,
        password: password
      }).then(function(data, status) {
        $window.sessionStorage["userInfo"] = JSON.stringify(data);
        return data;
      }, function(error, status) {
        console.log("Incorrect login");
        throw error;
      });
    }
  };
});

$scope.login = function(email, password) {
  return AuthService.login(email, password).then(function(data) {
    return console.log("login function returned", data);
  }, function(err) {
    return console.log("There was an error " + err);
  });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM