chan chan - 3 years ago 123
AngularJS Question

Function defined in a service is not a function angularjs

I have a controller Device Controller. I am trying to access a function in service but I am getting an error -
TypeError: DeviceService1.addNewDevice is not a function
at ChildScope.$scope.submitDeviceDtls (CreateDeviceCtrl.js:175)

Here's my code

$scope.submitDeviceDtls = function () {

if ($scope.isNewDevice) {
DeviceService1.addNewDevice($scope.device).then(
function (res) {
console.log(JSON.stringify(res));
// logic
}
}
}


I have a service DeviceService1

function ($http, $q, ApiService, AuthService) {

return {

addNewDevice: function (deviceDtls) {
var deferred = $q.defer();

var payload = new FormData();

payload.append('deviceDtls', new Blob([JSON
.stringify(deviceDtls)], {
type: "application/json"
}));
// payload.append('profilePic', profile_pic);
payload.append('doctorId', AuthService.getDoctorId());
var req = {

method: 'POST',
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity,
responseType: 'arraybuffer',
data: payload
}

ApiService.generic_post('/device/', req).then(
function (res) {

deferred.resolve(res);

}, function (error) {

deferred.reject(error);
}
);

return deferred.promise;

}

return DeviceService1;


Can someone help me? TIA

Answer Source

At your DeviceService1 you are returning firstly an object with the properties you need which includes the function (addnewDevice) you are trying to call but afterwards you return DeviceService1 (return DeviceService) which overrides the first return.

Just remove the following part:

return DeviceService1;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download