【问题标题】:Meteor-Angular Service functionMeteor-Angular 服务功能
【发布时间】:2015-09-04 01:01:08
【问题描述】:

我正在 Angular-Meteor 中创建一个应用程序,我想在我的服务中创建一些可以在我的控制器中使用的函数。然而,这些函数使用 $meteor.subscribe 函数,它查询数据库并返回一个回调。在我的控制器中,我想调用该函数并将其绑定到 $scope,但随后它返回未定义,因为回调尚未返回任何内容。是否有将代码保留在服务中的解决方案?有什么建议吗?

一个例子:

服务

angular.module('GQ').service('AuthService', ['$meteor', function($meteor)
{

    console.log('AuthService init')

    this.getUserAuth = function() {

        var user = {};
        $meteor.subscribe('isAdmin').then(function(res){
            //do database query...

            //loop over returned values and do a check if query matches or not
            // if it does match return true
            // else return false



        });

        // then return the value

        return user.isAdmin;
    }


}]);

控制器

$scope.isAdmin = AuthService.getUserAuth();
console.log($scope.isAdmin) <--- undefined

【问题讨论】:

  • 实际上这是由于 ajax 调用的async 行为而发生的。你应该试试$q 服务。

标签: angularjs meteor


【解决方案1】:

您可以使用角度承诺 (official doc)。

您的服务示例:

this.getUserAuth = function() {
    var deferred = $q.defer();
    var user = {};
    $meteor.subscribe('isAdmin').then(function(res, err){
        // ....

        // just an example
        if (!res.isAdmin) deferred.reject('not an admin');

        if (err) deferred.reject(err);
        else deferred.resolve(res);

    });
    return deferred.promise;
}

在您的控制器中使用:

AuthService.getUserAuth()
   .then(function(res){
       console.log(res); // the res from service
       $scope.isAdmin = res; // is asynchronous, but angular updates the scope var
    }, function(err){
       // error handling here
    });

【讨论】:

  • 这是推荐的做法吗?我还想将代码保留在@Marciano 等服务/工厂文件中
  • 这样您就可以将代码保存在服务和工厂文件中(推荐)。我不知道 MeteorJs 的建议,但我已经多次看到这一点,并且在 javascript 中建议将 Promises 用于异步进程。另一种方法是使用回调。
  • @dork 是的,这是推荐的做法。将数据导入服务很方便,因为您只需将服务注入控制器并在不同控制器之间共享数据。控制器不应该进行数据获取。它应该只将数据绑定到视图。
  • @fdelia @Marciano 谢谢!我在应该在服务/工厂中的控制器中看到很多 Meteor.calls,并且想知道如何分离代码。
猜你喜欢
  • 2014-04-04
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 2016-06-04
  • 1970-01-01
相关资源
最近更新 更多