Angular js .then is not a function - javascript

I have this service that loads data..
angular.module('App').service('daysService', ['$http','$q',function($http,$q) {
var days = [];
return {
loadDay: function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
});
}
};
}]);
than in the controller i call the service
daysService.loadDay.then(function(data) {
alert(data)
});
But i'm getting this error TypeError: daysService.loadDay.then is not a function
Any suggestion?

You are not returning anything from your loadDay function. Try this:
return {
loadDay: function() {
return $http({ // <-- return the promise
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
});
}
};

daysService.loadDay.then(function(data) {
alert(data)
});
On the first line you are not calling loadDay like a function you are accessing it as a property. so you need to change it to this:
daysService.loadDay().then(function(data) {
alert(data)
});
Note the parenthesis on loadDay.
Secondly, you are using a service like a factory. So you have two options:
angular.module('App').service('daysService', ['$http','$q',function($http,$q) {
var days = [];
this.loadDay = function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
});
};
}]);
OR
angular.module('App').factory('daysService', ['$http','$q',function($http,$q) {
var days = [];
return {
loadDay: function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
});
}
};
}]);
Finally, you aren't returning the promise from the function:
function() {
return $http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function(data) {
console.log('Error checking server.');
});
};
And if I were doing this, I would do:
angular.module('App').factory('daysService', ['$http', '$q', function($http, $q) {
var days = [];
this.loadDay = function() {
return $http.get('/app/days/list/').then(
function(data) {
days.push(data);
return days;
},
function(data) {
console.log('Error checking server.');
}
);
};
}]);

Your factory should return a promise instead of days if you want to use .then(). I believe you can do something like return $q.when(days) instead of return days and that should work.
Also just to note, .success() and .failure() callbacks are deprecated as of Angular 1.4. Not sure which version you're using, but $http now uses .then following this pattern:
$http({stuff}).then(function successCallback(response) {
//success
}, function errorCallback(response) {
// error
});

angular.module('App').service('daysService', ['$http','$q',function($http,$q) {
var days = [];
return {
loadDay: function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
//return days;
}).error(function (data) {
console.log('Error checking server.');
});
},getDays: function(){ return days; }
};
}]);
daysService.loadDay(); $window.alert(daysService.getDays());

If you create a promise only then will you be able to use it with .then(). Check this document on how to create a promise. It is simple. https://docs.angularjs.org/api/ng/service/$q
You code is right now incapable of using .then() and the object/object property is not present so the error TypeError: daysService.loadDay.then is not a function. Else write a code that does not require you to use .then() but can work as normally triggered functions. That will work too.
/* In your service */
angular.module('App').factory('daysService', ['$http',function($http) {
var days = [];
return {
loadDay: function() {
$http({
method: 'get',
url: '/app/days/list/',
}).success(function(data) {
days.push(data);
return days;
}).error(function (data) {
console.log('Error checking server.');
return;
});
}
};
}]);
/* In your controller trigger the eventorclick */
$scope.trigger = function(){
$scope.modelname = daysService.loadDay(); /* returns days else undefined or null */
alert($scope.modelname); /* handle your issues if you have array of objects */
}

Related

How to interact between 2 config files

I have a config.prop file which is being called from ngConfig.js file which is a service file. This prop file contains an URL which I need in my 2nd service file ngContent.js .
These files are being called individually from resolve.
$routeProvider.
when('/login', {
templateUrl: 'views/login.html',
controller: LoginController,
resolve: {
urlData: function(Config) {
return Config.prop().then(function(response) {
return response;
});
},
contentData:function(Content){
return Content.prop().then(function(response){
return response;
});
}
}
})
The response I am getting from urlData, which is resolving my response from ngConfig.js is the content of the config.prop. I need this response in my ngContent.js file.
The content of ngConfig.js is
angular.module('ngConfig', [])
.service('Config', function ($http, $rootScope, $document) {
//API calling method for all method
this.prop = function () {
try {
//API calling
var promise = $http({
method: 'GET',
dataType: "application/json",
data: 'json',
cache: false,
url: 'config.prop',
}).then(function (response) {
return response;
}, function (response) {
return response;
});
} catch (ex) {
return ex;
}
return promise;
};
});
The content of ngContent.js is
angular.module('ngContent', [])
.service('Content', function ($http, $rootScope, $document) {
//API calling method for all method
this.prop = function () {
try {
//API calling
var promise = $http({
method: 'GET',
dataType: "application/json",
data: 'json',
cache: false,
url: API_URL
}).then(function (response) {
return response;
}, function (response) {
return response;
});
} catch (ex) {
return ex;
}
return promise;
};
});
The API_URL is present in config.prop file, which is called from ngConfig.js file.
I hope I was able to present my problem clearly.
Thanks in advance.
You may pass urlData to contentData, like this, and then pass it to Content.prop().
contentData: function(Content, urlData){
return Content.prop(urlData).then(function(response){
return response;
});
}
Edit
This doesn't work with $routeProvider, you have to use $stateProvider of ui-router.
I have used it and it works. Use it the same way as discussed above.

Run HTTP post on successful post login

I have a simple login, once user is logged in I have added a call back to run another post so that I have access to the post json to use in my system.
I think the way I have done it is correct however I am getting error
GetData is not defined
Is this the correct way to do this
JavaScript
$scope.LogIn = function () {
$http({
url: "http://www.somesite.co.uk/ccuploader/users/login",
method: "POST",
data: $.param({'username': $scope.UserName, 'password': $scope.PassWord}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
GetData();
// location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
$scope.UserData = function ($scope) {
$scope.UserName = "";
$scope.PassWord = "";
};
$scope.GetData = function () {
$http({
url: " http://www.somesite.co.uk/ccuploader/campaigns/getCampaign",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log("then : " + JSON.stringify(response));
location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
You need to update your code to be $scope.GetData();.
Currently you are using GetData() which doesn't reference the same method. In fact it is undefined as per the error message.

How to chain multiple separate JavaScript functions

I know similar questions have been asked before but none of the examples make sense to me. (Any I have found have failed to explain the basics for me with the clarity I need.)
I have four AngularJS functions. Each calls a REST service and does stuff that is unrelated to any of the other functions. E.g.
$scope.step1 = function() { $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
}).success(function (data, status, headers, config) {
$scope.step1data = data;
}).error(function (data, status, headers, config) {
$scope.logError(data);
});};
I would like to call the four functions in sequence
$scope.step1
$scope.step2
$scope.step3
$scope.step4
And catch any errors encountered.
I have narrowed the code to the below but it does not work for me. Any help would be greatly appreciated.
$scope.step1().then(function() {
$scope.step2();
}).then(function() {
$scope.step3();
}).then(function() {
$scope.step4();
}).catch(function(e) {
console.log(e);
});
You need to return the promise from each step function to your then() callback so that its resulting promise waits for that promise:
$scope.step1().then(function() {
return $scope.step2();
})...
First, change your step1, step2, step3 and step4 to return promises like below:
$scope.step1 = function() {
return $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})};
$scope.step2 = function() {
return $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})};
$scope.step3 = function() {
return $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})};
$scope.step4 = function() {
return $http({
method: 'GET',
url: "http://www/end/point",
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})};
Then, chain them together like this:
$scope.step1().then(function (step1data) {
$scope.step1data = step1data;
$scope.step2().then(function (step2Data) {
$scope.step2Data = step2Data;
$scope.step3().then(function (step3Data) {
$scope.step3Data = step3Data;
$scope.step4().then(function (step4Data) {
$scope.step4Data = step4Data;
});
});
});
})
You can mix asynchronous functions with any kind of logic that JavaScript offers if you execute your code synchronously via nsynjs. Here is how your code may need to be transformed:
Step 1: Wrap asynchronous function into generic nsynjs-aware wrapper:
// generic function to retrieve url
// ctx is a reference to caller pseudo-thread context
var httpUrl = function(ctx,url,$http) {
var res={};
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/jsonp;odata=verbose" }
})
.success(function (data, status, headers, config) {
res.data = data;
ctx.resume() // tells nsynjs to resume caller function
}).error(function (data, status, headers, config) {
ctx.resume(data) // resume caller function with exception
// or replace with these 2 lines if you don't want exception
// res.error = data;
// ctx.resume()
});
return res;
};
getUrl.nsynjsHasCallback = true; // this tells nsynjs engine that it
// should pause execution and wait until ctx.resume() is called from callback
Step 2. Write your logic as if it was synchronous, and put it into function:
function synchronousCode(param1, param2) {
var step1 = function() {
var data = httpUrl(nsynjsCtx,"nsynjs/examples/data/file1.json").data;
console.log("data is ready at this point:",data);
// do staff this data
return data;
};
var step2 = function() {
var data = httpUrl(nsynjsCtx,"nsynjs/examples/data/file2.json").data;
console.log("data is ready at this point:",data);
// do staff this data
return data;
};
console.log( step1(param1) + step2(param2) ); // do more staff with data
}
Step 3. Run your synchronous code via nsynjs:
nsynjs.run(synchronousCode,{},"value for param1","value for param1",function(){
console.log("Synchronous Code done");
})
More examples here: https://github.com/amaksr/nsynjs/tree/master/examples
You need to use promise, in your controller, you should inject $q which will handle promise.
angularApp.controller('YourController', ['$q', '$scope',
function ($q, $scope) {
$scope.firstFunction = function () {
var deferred = $q.defer();
//Do things you want here...
console.log(1);
deferred.resolve();
return deferred.promise;
};
$scope.secondFunction = function () {
var deferred = $q.defer();
//Do things you want here...
console.log(2);
deferred.resolve();
return deferred.promise;
};
$scope.firstFunction().then(function () {
$scope.secondFunction.then(function () {
console.log(3)
})
})
}]);
console logs in functions above will print out:
1
2
3

AngularJS http return value

I want to write a function in AngularJS that returns a value (actually it is a string). That value is returned by a http request, but async is driving me crazy.
My first attempt was:
this.readParameter = function(key) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
throw new Error("Error");
})
};
But of course it does not work because of Angular async features (response.data is undefined)
What is the way to do it? I just want to return the value (string), so I can use this function like
var a = readParameter("key1")
What you can do is define some variable with initial value outside function and on response set value inside success function instead of returning it.
Delegator pattern works great here to assign $http task to some service and use callback method for response.
Controller (Call Service for specific request) -> Service (Manage request params and other things and return factory response to Controller) -> Factory (Send request and return it to Service)
Basic example of Callback
var myVariable = '';
function myFunction (key, callback) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
callback(response);
}, function errorCallback(response) {
throw new Error("Error");
})
};
function myCallbackFunction(response) {
myVariable = response.data; // assign value to variable
// Do some work after getting response
}
myFunction('MY_KEY', myCallbackFunction);
This is basic example to set value but instead use callback pattern from above example.
var myvariable = '';
function myFunction (key) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
myvariable = response.data; // set data to myvariable
// Do something else on success response
}, function errorCallback(response) {
throw new Error("Error");
})
};
myFunction('MY_KEY');
Don't try to mix async and sync programming. Instead use a callback to use like
readParameter("key1", callback)
for example:
this.readParameter = function(key, callback) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
callback(response)
}, function errorCallback(response) {
throw new Error("Error");
})
};
I resolve this by using promise:
Example :
in Service (invoicesAPIservice => invoicesapiservice.js) you use:
angular.module('app')
.service('invoicesAPIservice', function ($http) {
this.connectToAPI= function () {
return new Promise(function(resolve,reject){
var options = {
method:'GET',
url :'',
headers:{
'X-User-Agent': '....',
'Authorization': '....',
}
};
$http(options).then(function successCallback(response) {
resolve(response);
//console.log(response);
},function errorCallback(response) {
reject(response);
})
});
});
});
and in your Controller (mainCtrl=> mainCtrl.js):
angular.module('app').controller('mainCtrl', function($scope,invoicesAPIservice) {
$scope.connectToAPI=function () {
invoicesAPIservice.connectToAPI().then(function (content) {
console.log(content.statusText);
}.catch(function (err) {
//console.log(err);
alert("Server is Out");
});
}
});
And in your page : index.html:
<button ng-click="connectToAPI()"></button>
:)

Consume AngularJS service from simple javascript

I have a main.js javascript file that has an init() function in.
I also have this AngularJS service:
(function () {
var app = angular.module('spContact', ['ngRoute']);
app.factory('spAuthService', function ($http, $q) {
var authenticate = function (userId, password, url) {
var signInurl = 'https://' + url + '/_forms/default.aspx?wa=wsignin1.0';
var deferred = $q.defer();
var message = getSAMLRequest(userId, password, signInurl);
$http({
method: 'POST',
url: 'https://login.microsoftonline.com/extSTS.srf',
data: message,
headers: {
'Content-Type': "text/xml; charset=\"utf-8\""
}
}).success(function (data) {
getBearerToken(data, signInurl).then(function (data) {
deferred.resolve(data);
}, function (data) {
deferred.reject(data)
})
});
return deferred.promise;
};
return {
authenticate: authenticate
};
function getSAMLRequest(userID, password, url) {
return 'envelope';
}
function getBearerToken(result, url) {
var deferred = $q.defer();
var securityToken = $($.parseXML(result)).find("BinarySecurityToken").text();
if (securityToken.length == 0) {
deferred.reject();
}
else {
$http({
method: 'POST',
url: url,
data: securityToken,
headers: {
Accept: "application/json;odata=verbose"
}
}).success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject();
});
}
return deferred.promise;
}
});
})();
How can I call this services "authenticate" method from the init() function of my main JavaScript file?
This service should return some authentication cookies that I would need for data querying.
You need to inject this factory to some controller/directive like:
app.controller('MyCtrl', ['spAuthService', function (spAuthService) {
spAuthService.authenticate.then(function (data) {
// ...
});
}]);
And this controller MyCtrl may be put on some home page and bootstrapped by Angular automatically.

Categories