2017-03-02 47 views
0

我想獲得用戶從。服務.controller價值的價值,我該怎麼辦呢?誰能幫忙?我怎樣才能得到。服務於.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; 
     } 
    }); 
    } 
} 

回答

1

這裏的調用setDatabase功能在pounchDB服務的例子:你需要返回一個用戶陣列,而不會將重新

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();

1

從你需要返回無極對象服務,這將解決或拒絕之後基於網絡的響應。您需要添加解析處理程序和拒絕處理程序以瞭解承諾異步響應。

一個模擬工作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 
    } 
}]);