“Cannot read property 'defer' of undefined”. error in AngularJs. Does anyone have a solution?

微笑、不失礼 提交于 2019-12-24 07:28:21

问题


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:


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.

Correct Code is attached below:

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;
    }
}

This will resolve your issues.

Cheers!!!




回答2:


You are passing $q as an argument to your getCustomers function. $q is automatically available in all the functions in your service.

Also, change CustomerService($q) to CustomerService($q, $http)




回答3:


function CustomerService($q){
    return {
        getCustomers: getCustomers($q)
    }
}


来源:https://stackoverflow.com/questions/38418121/cannot-read-property-defer-of-undefined-error-in-angularjs-does-anyone-hav

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!