【问题标题】:How can i get the value from .service in .controller如何从 .controller 中的 .service 获取值
【发布时间】:2017-03-02 11:58:42
【问题描述】:

我想从 .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;
        }
    });
  }
}

【问题讨论】:

    标签: angularjs pouchdb


    【解决方案1】:

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

    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.";
      }  
    });
    <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>

    然后在您的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();

    【讨论】:

      【解决方案2】:

      您需要从服务中返回 Promise 对象,该对象稍后将根据网络响应解决或拒绝。您需要添加解析处理程序和拒绝处理程序才能知道承诺异步响应。

      模拟工作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
        }
      }]);
      

      【讨论】:

        猜你喜欢
        • 2021-11-13
        • 2015-09-30
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多