简体   繁体   中英

how to pass parameters to a function in a service in angular

I'm trying to pass parameters to a service in angular, but angular completly breaks when I am doing it.

Can someone please tell me what I am doing wrong?

This is my service:

function AlertData($http){


var AlertData = {};
  var settings = {
    }
  }

  // Registering client by its reference, housnumber and postalcode
  AlertData.getData = function(reference, housnumber, postalcode) {//These paramaters are not comming through
    settings.url = "url";
    settings.data = { "data": { "attributes": { "reference": reference, "huisnummer": housnumber, "postcode": postalcode } } };
    return $http(settings);
  };

  return AlertData;
}

alertApp.factory('alertData', AlertData);

And the controller function where from I try to pass the parameters

// Registering client
  alertData.getData(clientReference, housnumber, post)
    .then(function(data){
      if(data.status==201){
        getClientByReference();
      } else {
        $scope.dataError = standaardError;
      }
    })
    .catch(function(data, status, headers, config){
      $scope.dataError = standaardError;
    });

UPDATE This is the error that i'm getting

Error: [ng:areq] Argument 'fn' is not a function, got Object
http://errors.angularjs.org/1.4.7/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20Object
    at angular.js:68
    at assertArg (angular.js:1796)
    at assertArgFn (angular.js:1806)
    at Function.annotate [as $$annotate] (angular.js:3765)
    at Object.invoke (angular.js:4456)
    at Object.enforcedReturnValue [as $get] (angular.js:4330)
    at Object.invoke (angular.js:4478)
    at angular.js:4295
    at getService (angular.js:4437)
    at Object.invoke (angular.js:4469)

UPDATE 2 This is what i want to do: In C# you can do something like this: Make a service with functions than call it like this myService.myFunction(myPararameters) this is what i like to achieve with angular, but I don't know how

I don't know where you're referring the code but I haven't seen this kind of structure.

Below is what in general everyone use to define a factory

function AlertData($http) {
    var obj = {};
    // Registering client by its reference, housnumber and postalcode
    obj.getData = function(reference, housnumber, postalcode) {
        settings.url = "url";
        settings.data = {
            "data" : {
                "attributes" : {
                    "reference" : reference,
                    "huisnummer" : housnumber,
                    "postcode" : postalcode
                }
            }
        };
        return $http(settings);
    }

    return obj;
}

alertApp.factory('alertData', AlertData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM