簡體   English   中英

從Angular的工廠方法返回響應給控制器

[英]Returning response to controller from factory method in Angular

我有一個名為Auth的工廠,它的方法Auth.signIn()通過我的解耦API進行身份驗證。 該部分有效,我正在嘗試捕獲響應,即用戶信息。 從控制器調用工廠是可行的,但是我似乎無法捕獲該方法的響應。

調節器

.controller('DashCtrl', function($scope, Auth) {
  //OAUTH SIGN IN
  $scope.signIn = function() {
    $scope.currentUser = Auth.signIn()
    //^^Auth.signIn() is happening but $scope.currentUser is undefined when I try to access it in the view
  }
  //OAUTH SIGN OUT
  $scope.signOut = function() {
    Auth.signOut()
  }

})

.factory('Auth', function($auth) {
  var user = null
  return {
    signIn: function() {
      $auth.authenticate('google')
      .then(function(response) {
        return response //trying to catch this in the controller with currentUser = Auth.signIn()
        //verified that response is the user data
      })
      .catch(function(resp) {
        // handle errors
      })
    }
})

我是有角度的新手,所以任何幫助和指導都將不勝感激。 我正在嘗試使我的代碼/問題盡可能簡潔。 預先感謝您的幫助。

首先,在工廠的signIn函數中,應返回諾言

signIn: function() {
      return $auth.authenticate('google')
      .then(function(response) {
        return response.data;
      });
    }

然后在您的控制器中,在Auth.signIn之后Auth.signIn currentUser初始化

$scope.signIn = function() {
    Auth.signIn().then(function(data) {
      $scope.currentUser = data;
    }
  }

暫無
暫無

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

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