问题描述
在我的服务"customerService"中,我注入了$ q对象,该对象公开了延迟的对象.在我的函数"getCustomers"中,我尝试检索延迟的对象,但收到错误:运行$ q.defer()方法时,无法读取未定义的属性'defer'".我已经研究过类似的关于stackoverflow的解决方案,但是还没有足够的解决方案.造成此错误的原因是什么?
In my service "customerService" I am injecting the $q object which exposes the deferred object. In my function "getCustomers" I am trying to retrieve the deferred object but I receive an error: "Cannot read property 'defer' of undefined" when I run the $q.defer() method. I have already looked at similar solutions on stackoverflow but none were adequate. What could be the cause of this error?
var mysql = require("mysql");
//creates sql database connection
var connection = mysql.createConnection(
{
host:"localhost",
database: "customer_manager"
}
);
angular.module('app')
.service('customerService', ['$q','$http', CustomerService]);
function CustomerService($q){
return {
getCustomers: getCustomers
}
}
function getCustomers($q){
var deferred = $q.defer();
var query = "SELECT * FROM customers";
connection.query(query, function(err, res){
if(err) deferred.reject(err);
deferred.resolve(res);
});
return deferred.promise;
}
推荐答案
问题:1.您已经注入了$ q服务来注册服务,因此不需要显式传递函数参数.2.如果是角度服务,则必须将所有公开的API与 this 相关联,而不是将其返回.否则它将无法正常工作.如果有角度工厂,我们将返回公开的API.
Issues:1. You have already injected $q service which registering service so there is no need to explicit pass in the function arguments.2. In case of angular service, you will have to associate all exposing APIs to this instead return that. Else it will not work. We return exposing APIs in case of angular factory.
angular.module('app')
.service('customerService', ['$q','$http', CustomerService]);
function CustomerService($q, $http){
this.getCustomers = function(){
var deferred = $q.defer();
var query = "SELECT * FROM customers";
connection.query(query, function(err, res){
if(err) deferred.reject(err);
deferred.resolve(res);
});
return deferred.promise;
}
}
这将解决您的问题.
干杯!
这篇关于“无法读取未定义的属性'defer'".AngularJs中的错误.有没有人有办法解决吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!