如何在.controller中获取.service的值

时间:2017-03-02 02:55:19

标签: angularjs pouchdb

我想从.service获取.controller中用户的价值,我该怎么做?有人可以帮忙吗?

app.controller("myCtrl", function($scope, $http, $pouchDB) {
    $pouchDB.setDatabase("infoDB");
    $pouchDB.allDocs();
}

app.service("$pouchDB", ["$rootScope", "$q", function($rootScope, $q) {
  this.allDocs = function(docs){
    database.allDocs({
        include_docs: true
    })
    .then (function(result){
        for (var i = 0; i < result.rows.length; i++){
            var users = result.rows[i].doc;
        }
    });
  }
}

2 个答案:

答案 0 :(得分:1)

以下是在setDatabase服务中调用pounchDB函数的示例:

&#13;
&#13;
var app = angular.module('app', []);

app.controller('myCtrl', function($scope, pouchDB) {
  var result = pouchDB.setDatabase("infoDB");
  console.log(result);  
});

app.service('pouchDB', function() {   
  this.setDatabase= function(db){
    return db + " was called.";
  }  
});
&#13;
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>

<div ng-app="app">
    <div ng-controller="myCtrl">
    </div>
</div>
&#13;
&#13;
&#13;

然后在你的allDocs函数中,你需要返回一个用户数组,而不是继续在循环中重新分配它:

.then (function(result){
    var users = [];
    for (var i = 0; i < result.rows.length; i++){
        users.push(result.rows[i].doc);
    }
    return users;
});

换句话说,您错过了setDatabase()功能;在allDocs()函数中,您需要return users个结果数组;在您的控制器中,您需要收到值:$scope.result = $pouchDB.allDocs();

答案 1 :(得分:1)

从服务中您需要返回Promise对象,该对象将根据网络响应稍后解析或拒绝。您需要添加解析处理程序并拒绝处理程序以了解promise async响应。

模拟工作plunker

app.controller("myCtrl", function($scope, $http, $pouchDB) {
  $pouchDB.setDatabase("infoDB");
  //resolve handler and reject handler to thenable object
  $pouchDB.allDocs().then(function(result) {
    $scope.users = [];
    for (var i = 0; i < result.rows.length; i++) {
      $scope.users.push(result.rows[i].doc);
    }
  },
  function(err){console.log('error')}
  );
});

app.service("$pouchDB", ["$rootScope", "$q", function($rootScope, $q) {
  this.allDocs = function(docs) {
    return database.allDocs({
      include_docs: true
    }); //return promise
  }
}]);