将数据从 CouchDB 服务传递到 AngularJS 中的控制器
pass data from PouchDB Service to Controller in AngluarJS
我在 Angular/Ionic 中设置了一个 PouchDb 服务,该服务在该服务中运行良好,但当我尝试将从 PouchDB 服务检索的数据传递到我的控制器时失败。
这是我的服务
angular.module('myApp', [])
.service('DBService', function($q) {
var items;
var db;
var self = this;
this.initDB = function() {
return db = new PouchDB('simpleDB', {
adapter: 'websql'
});
};
this.storeData = function() {
return $q.when(
db.put({
_id: 'mydoc',
title: 'some text'
}).then(function (response) {
// handle response
console.log('done')
}).catch(function (err) {
console.log(err);
})
)
};
this.getData = function(){
return $q.when(
db.get('mydoc').then(function (doc) {
// handle doc
console.log(doc); // I see the data in console
}).catch(function (err) {
console.log(err);
})
)
}
})
这是控制器
angular.module('myApp', [])
.controller('mainCtrl', function($scope, DBService, $q) {
$scope.getData = function(){
DBService.initDB()
DBService.getData().then(function(data){
console.log(data)
})
}
当我使用 then() 时出现错误 TypeError: Cannot read 属性 'then' of undefined.
谁能帮我弄清楚如何将数据从我的服务正确传递到控制器?
我很幸运能很快找到错误!我没有 return 在我的服务中获取数据,所以我将其更改为
this.getData = function(){
return $q.when(
db.get('mydoc').then(function (doc) {
// handle doc
return doc; // I added this
console.log(doc); // I see the data in console
}).catch(function (err) {
console.log(err);
})
)
}
而 then() return 未定义的原因是我不小心从 this.getData 函数的第二行省略了 return $q.when( !现在我在控制器中有了我需要的数据!
我在 Angular/Ionic 中设置了一个 PouchDb 服务,该服务在该服务中运行良好,但当我尝试将从 PouchDB 服务检索的数据传递到我的控制器时失败。
这是我的服务
angular.module('myApp', [])
.service('DBService', function($q) {
var items;
var db;
var self = this;
this.initDB = function() {
return db = new PouchDB('simpleDB', {
adapter: 'websql'
});
};
this.storeData = function() {
return $q.when(
db.put({
_id: 'mydoc',
title: 'some text'
}).then(function (response) {
// handle response
console.log('done')
}).catch(function (err) {
console.log(err);
})
)
};
this.getData = function(){
return $q.when(
db.get('mydoc').then(function (doc) {
// handle doc
console.log(doc); // I see the data in console
}).catch(function (err) {
console.log(err);
})
)
}
})
这是控制器
angular.module('myApp', [])
.controller('mainCtrl', function($scope, DBService, $q) {
$scope.getData = function(){
DBService.initDB()
DBService.getData().then(function(data){
console.log(data)
})
}
当我使用 then() 时出现错误 TypeError: Cannot read 属性 'then' of undefined.
谁能帮我弄清楚如何将数据从我的服务正确传递到控制器?
我很幸运能很快找到错误!我没有 return 在我的服务中获取数据,所以我将其更改为
this.getData = function(){
return $q.when(
db.get('mydoc').then(function (doc) {
// handle doc
return doc; // I added this
console.log(doc); // I see the data in console
}).catch(function (err) {
console.log(err);
})
)
}
而 then() return 未定义的原因是我不小心从 this.getData 函数的第二行省略了 return $q.when( !现在我在控制器中有了我需要的数据!