如何让控制器等待 return 值的服务以及如何访问控制器中的 returned 值?

How to make controller wait for service to return a value and how to access the returned value in controller?

我是 angularjs 的新手。我在访问其控制器 中的 angularjs 服务返回的 值时遇到问题。 控制器中的代码如下:

'use strict';
app.controller('AdminTaskCtrl', function ($scope, Search) {
    $scope.buildEnquiry = function (collegeId, ) {
        Search.getIdByEmail(collegeId).then ( function ( result ) {
            $scope.uId = result;
            console.log($scope.uId);
        });
    };
});//controller ends here

而搜索服务中的代码如下:

'use strict';
           app.factory('Search',function ($firebase, FIREBASE_URL, $rootScope) {
                          var simpleuser = "";
                          getIdByEmail: function(counsellorEmail) {
                          var collegeuserArray = ($firebase(new Firebase(FIREBASE_URL+"abc/def/")).$asArray());
                          collegeuserArray.$loaded(function(collegeuserArray) {
                              for(var i=0; i<collegeuserArray.length; i++) 
                              {
                                if((collegeuserArray[i].$value) == counsellorEmail)
                                {
                                     simpleuser = collegeuserArray.$keyAt(collegeuserArray[i]);
                                     console.log(simpleuser);
                                     return simpleuser;
                                }
                              }
                          }, function(error) {
                              console.error("Error:", error);
                          });
                    }
                  };     
            );//service ends here.

当代码执行时,它会给出错误。then function as fallows:

TypeError: undefined 不是函数 并且控制器中的值未被访问。

请帮忙。

'use strict';
       app.factory('Search',function ($firebase, FIREBASE_URL, $rootScope, $q) {
                      var simpleuser = "";
                      getIdByEmail: function(counsellorEmail) {
                      var deferred = $q.defer();
                      var collegeUserArray = ($firebase(new Firebase(FIREBASE_URL+"abc/def/")).$asArray());
                      collegeUserArray.$loaded(function(collegeUserArray) {
                          for(var i=0; i<collegeUserArray.length; i++) 
                          {
                            if((collegeUserArray[i].$value) == counsellorEmail)
                            {
                                 simpleUser = collegeUserArray.$keyAt(collegeUserArray[i]);
                                 console.log(simpleUser);
                                 //return simpleUser;
                                 deferred.resolve(simpleUser);
                            }
                          }
                      }, function(error) {
                          console.error("Error:", error);
                          deferred.reject(error);
                      });
                      return deferred.promise;
                }
              };     
        );

还有你的控制器

'use strict';
app.controller('AdminTaskCtrl', function ($scope, Search) {
  $scope.buildEnquiry = function (collegeId, ) {
    Search.getIdByEmail(collegeId).then ( function ( result ) {
        $scope.uId = result;
        console.log($scope.uId);
    }, function(error){
        //If an error happened, handle it here
    });
  };
});

要直接回答您的问题,$loaded returns a promise,所以这里最简单的答案是 return 从您的服务中获取它,而不用费心 $q 和所有这些其他事情.

这里的整个前提似乎确实存在缺陷,XY problem. It seems like several hacks intended to subvert the intended usage of these libs, and like a good, solid read of the Angular walkthrough and the AngularFire guide 会在这里省去很多痛苦和不必要的复杂性。

这里使用factory是一种颠覆,重耦合。语法无效,无法编译。最终,目标是向从 AngularFire 编辑的同步数组 return 添加一个搜索方法,这应该通过 $extendFactory 来完成。

app.factory('firebaseRef', function(FIREBASE_URL) {
   return function(path) {
      var ref = new Firebase(FIREBASE_URL);
      if( path ) { ref = ref.child(path); }
      return ref;
   }
});

app.factory('SearchableArray', function($firebase, $FirebaseArray) {
   var ArrayWithSearch = $FirebaseArray.$extendFactory({
     searchByEmail: function(emailAddress) {
        var res = null;
        for(var i=0, len=this.$list.length; i < len; i++ ) {
           if( this.$list[i].email === emailAddress ) {
              res = this.$list[i];
              break;
           }
        }
        return res;
     }
   });

   return function(ref) {
      return $firebase(ref, {arrayFactory: ArrayWithSearch}).$asArray();      
   }
});

app.controller('Controller', function($scope, SearchableArray, firebaseRef) {
   $scope.data = SearchableArray( firebaseRef('abc/def') );

   $scope.search = function(email) {
      console.log( $scope.data.searchByEmail(email) );
   };
});